import os
import sys
import c4d
import colorsys
import time
import math
import time

from c4d import documents, utils, gui, plugins, modules
from xml.dom.minidom import parseString
from xml.parsers.expat import ExpatError

PLUGIN_ID 				= 1033601
AUTH_PLUGIN_ID       	= 1033606
CONFIG_PLUGIN_ID     	= 1033602

DLG_IMPORT	 			= 950000
IDC_CB_VRAY				= 950001
IDC_CB_OCTANE			= 9500012
IDC_CB_STD				= 950002
IDC_CB_STDQUICK			= 950003
IDC_BT_OK				= 950004
IDC_CB_OPTIONS			= 950005
CB_OP_CURRENT_ID        = 13132001
NUM_PA_CURRENT_ID       = 13132002
CB_UT_CURRENT_ID        = 13132003
NUM_EA_CURRENT_ID       = 13132004
CB_UP_CURRENT_ID        = 13132005
DIR_CURRENT_ID			= 13132010

#----------------------- Utility Classes ----------------------------------

class ImportMessageDialog(c4d.gui.GeDialog):
    
    def CreateLayout(self):
        print "Dialog Start"
        dlg_res = c4d.plugins.GeResource()
        dlg_res.Init(c4d.storage.GeGetPluginPath())
        result = self.LoadDialogResource(DLG_IMPORT, None, flags=c4d.BFH_SCALEFIT | c4d.BFV_SCALEFIT)
        #If VRayConverter Command Doesn't Exist..
        if not c4d.GetCommandName(1021144):
            #Hide VRay Option
            self.Enable(950001, False)
        return result
    
    def InitValues(self):
        #If VRayConverter Command Doesn't Exist..
        if not c4d.GetCommandName(1021144):
            #Vray Not Found Default to Standard
            self.SetBool(IDC_CB_VRAY,0);
            self.SetBool(IDC_CB_OCTANE,0);
            self.SetBool(IDC_CB_STD,1);
        else:
            #Vray Found Default to Vray
            self.SetBool(IDC_CB_VRAY,1);
            self.SetBool(IDC_CB_OCTANE,0);
            self.SetBool(IDC_CB_STD,0);
        self.SetBool(IDC_CB_STDQUICK,0);
        self.SetBool(IDC_CB_OPTIONS,0);
        Import.IMPORT_MODE = 1;
        return True
    
    def Command(self, id, msg):
        
        if id == IDC_BT_OK:
            if self.GetLong(IDC_CB_VRAY)==1:
                Import.IMPORT_MODE = 1;
            if self.GetLong(IDC_CB_OCTANE)==1:
                Import.IMPORT_MODE = 2;
            if self.GetLong(IDC_CB_STD)==1:
                Import.IMPORT_MODE = 3;
            if self.GetLong(IDC_CB_STDQUICK)==1:
                Import.IMPORT_MODE = 4;
            if self.GetBool(IDC_CB_OPTIONS):
                Import.IMPORT_OPTIONS = True;
            else:
                Import.IMPORT_OPTIONS = False;
            print ("MODE = "+str(Import.IMPORT_MODE))
            self.Close();
        
        return True

class XmlStandardAttribute(object):   
    def __init__(self, name, desc, setFunction, vrayAttribute=False, vrayConvert=None, modifierFunction=None, modifierParam=None):
        self.name = name
        self.desc = desc
        self.setFunction = setFunction
        self.vrayAttribute = vrayAttribute
        self.vrayConvert = vrayConvert
        self.modifierFunction = modifierFunction
        self.modifierParam = modifierParam
        
class XmlMaterialAttribute(object):
    def __init__(self, name, desc, use=None, setFunction=None, modifierFunction=None, modifierParam=None, vrayConvert=None):
        self.name = name
        self.desc = desc
        self.use = use
        self.setFunction = setFunction
        self.modifierFunction = modifierFunction
        self.modifierParam = modifierParam
        self.vrayConvert = vrayConvert

class XmlShaderTypeAttribute(object):    
    def __init__(self, name, desc, vrayAttribute=False):
        self.name = name
        self.desc = desc
        self.vrayAttribute = vrayAttribute

class XmlShaderAttribute(object):    
    def __init__(self, shaderName, desc, setFunction, vrayAttribute=False, modifierFunction=None, modifierParam=None):
        self.shaderName = shaderName
        self.desc = desc
        self.setFunction = setFunction
        self.vrayAttribute = vrayAttribute
        self.modifierFunction = modifierFunction
        self.modifierParam = modifierParam

class XmlLightAttribute(XmlStandardAttribute):
    def __init__(self, name, desc, setFunction, vrayAttribute=False, vrayConvert=None, modifierFunction=None, modifierParam=None):
        super(XmlLightAttribute, self).__init__(name, desc, setFunction, vrayAttribute, vrayConvert, modifierFunction, modifierParam)

class XmlCamAttribute(XmlStandardAttribute):
    def __init__(self, name, desc, setFunction, vrayAttribute=False, vrayConvert=None, modifierFunction=None, modifierParam=None):
        super(XmlCamAttribute, self).__init__(name, desc, setFunction, vrayAttribute, vrayConvert, modifierFunction, modifierParam)
    
class XmlRenderAttribute(XmlStandardAttribute):
    def __init__(self, name, desc, setFunction, vrayAttribute=False, vrayConvert=None, modifierFunction=None, modifierParam=None):
        super(XmlRenderAttribute, self).__init__(name, desc, setFunction, vrayAttribute, vrayConvert, modifierFunction, modifierParam)

#--------------------------------------------------------------------------
#------------------------- Main IMPORT Class ------------------------------
#--------------------------------------------------------------------------

class Import(c4d.plugins.CommandData):
    
    VRAY3                = False
    CB_OP_DEFAULT        = True
    CB_AP_DEFAULT        = True
    CB_UT_DEFAULT        = True
    NUM_EA_DEFAULT       = 0.1
    CB_UP_DEFAULT        = False
    
    CB_OP_CURRENT        = True
    CB_AP_CURRENT        = True
    CB_UT_CURRENT        = True
    NUM_EA_CURRENT       = 0.1
    CB_UP_CURRENT        = False
    CD_CURRENT           = 23
    
    DSET = 102114
    
    R16 = True
    R18 = False
    
    REFLECTION_LAYERID = 4
    
    currentMat = None
    currentSlot = None
    
    XML_PATH = "C:\\Temp\material.xml"
    ENCRYPTION = False
    ENCRYPTION_OFFSET = 10
    MATERIAL = "material"
    LIGHTMATERIAL = "vraylightmtl"
    OVERRIDEMATERIAL = "overridematerial"
    TWOSIDEDMATERIAL = "twosidedmaterial"
    FASTSSS2MATERIAL = "fastsss2material"
    BLENDMATERIAL = "blendmaterial"
    GEOMETRY = "geometry"
    VRAYPROXY = "vrayproxy"
    CAMERA = "camera"
    WIRECOLOR = "wirecolor"
    LIGHT = "light"
    VRAYSUN = "vray_sun"
    RENDER = "rsettings"
    NAME = "name"
    VRAY = "vray"
    SHADER_TYPE = "type"
    DATA = "name"
    VISIBLE = 102114
    VRAY_CONVERTER = 1021144
    OCTANE_LIGHT_TAG = 1029526
    OCTANE_CAMERA_TAG = 1029524
    VRAY_LIGHT_TAG = 1020441
    VRAY_CAMERA_TAG = 1020898
    VRAYBRIDGE = 1019782
    OCTANE = 1029525
    VRAYSHADER = 1026701
    BASECONT = 1248331028
    
    VRAY_USE_REFRACTION = 11111
    VRAY_REFR_TEXTUREMULT = 1111
    
    STD_LOCKGLOSS = False
    
    __dialog = None
    
    _tempObjects = []
    
    # The following list is mats ( such as newly created blend mats ) that the function _applyMultiSubMatsCorrectly should not replace
    _tagMatsDoNotReplace = []
    
    standardList = None
    bc = None
    
    _materialAttributes = None
    _blendmaterialAttributes = None
    _lightAttributes = None
    _vrayLightAttributes = None
    
    _renderTags = None
    _materialTags = None
    
    _stdReflectionChanged = False
    _standardMultiplier = 20672.12
    _expertMultiplier = 12764.25
    _metric = "inches"
    _metricStandard = 1
    _metricMultiplier = 0.383
    _metricDivider = 0.383
    _systemScale = 252.5
    _newSystemScale = 0
    _shaderTypes = None
    _shaderDestinations = None
    _shaderAttributes = None
    _shaderDests = None
    _vrayShaderAttributes = None
    _shaderStr = None
    
    _lightStr = None
    _vrayLightStr = None
    _materialStr = None
    _blendaterialStr = None
    _vrayMaterialStr = None
    _vrayRenderStr = None
    
    _stdChannels = None
    _vrayChannels = None
    
    _fileUnits = ""
    _metricScale = 0
    _unitMultiplier = 0
    
    _doc = None
    _importRenderMode = None
    _filePath = None
    _quickMode = False #
    _usingOctane = False #
    _vrayMaterials = False #
    _vrayLights = False #
    _vrayCameras = False #
    
    createdBlendMatList = []
    
    #----------------------- XML keywords --------------------------------------
     
    def _initLightArray(self):
        """Store each recognized light attribute in xml.
        """
                
        self._lightStr =    {
                #----- std_str : std_desc
                ("type", "omni") : c4d.LIGHT_TYPE_OMNI,
                ("type", "spot") : c4d.LIGHT_TYPE_SPOT,
                ("type", "infinite") : c4d.LIGHT_TYPE_DISTANT,
                ("type", "parallel") : c4d.LIGHT_TYPE_PARALLEL,
                ("type", "area") : c4d.LIGHT_TYPE_AREA,
                ("type", "ies") : c4d.LIGHT_TYPE_PHOTOMETRIC,
                ("area_type", "plane") : c4d.LIGHT_AREADETAILS_SHAPE_RECTANGLE, 
                ("area_type", "hemisphere") : c4d.LIGHT_AREADETAILS_SHAPE_HEMISPHERE,
                ("area_type", "sphere") : c4d.LIGHT_AREADETAILS_SHAPE_SPHERE,
                ("area_type", "mesh") : c4d.LIGHT_AREADETAILS_SHAPE_OBJECT,
                ("shadow", "none") : c4d.LIGHT_SHADOWTYPE_NONE,
                ("shadow", "area") : c4d.LIGHT_SHADOWTYPE_SOFT, #c4d.LIGHT_SHADOWTYPE_AREA,
                ("shadow", "raytraced") : c4d.LIGHT_SHADOWTYPE_SOFT, #c4d.LIGHT_SHADOWTYPE_HARD,
                ("shadow", "shadowmap") : c4d.LIGHT_SHADOWTYPE_SOFT
                            }
        
        self._lightAttributes =     [
                XmlLightAttribute("on", c4d.ID_BASEOBJECT_GENERATOR_FLAG, self._boolFunc),
                XmlLightAttribute("multiplier", c4d.LIGHT_BRIGHTNESS, self._floatFuncDivCien),
                XmlLightAttribute("type", c4d.LIGHT_TYPE, self._lightStrTypeFunc),
                XmlLightAttribute("color", c4d.LIGHT_COLOR, self._colorFunc),
                XmlLightAttribute("shadow", c4d.LIGHT_SHADOWTYPE, self._lightStrTypeFunc),
                XmlLightAttribute("width", c4d.LIGHT_AREADETAILS_SIZEX, self._floatFunc, modifierFunction=self._convertAreaLightSize),
                XmlLightAttribute("height", c4d.LIGHT_AREADETAILS_SIZEY, self._floatFunc, modifierFunction=self._convertAreaLightSize),
                XmlLightAttribute("height", c4d.LIGHT_AREADETAILS_SIZEZ, self._floatFunc, modifierFunction=self._convertAreaLightSize),
                XmlLightAttribute("ies_intensity_type", c4d.LIGHT_PHOTOMETRIC_UNIT, self._intFuncPut1),
                XmlLightAttribute("ies_intensity_value", c4d.LIGHT_PHOTOMETRIC_INTENSITY, self._floatFuncDivCien),
                XmlLightAttribute("ies_filename", c4d.LIGHT_PHOTOMETRIC_FILE, self._stdIESFilenameAndEnable),
                                    ]
        if self._usingOctane:
            self._octLightAttributes =     [
                    XmlLightAttribute("on", c4d.ID_BASEOBJECT_GENERATOR_FLAG, self._boolFuncTagParent),
                    XmlLightAttribute("multiplier", c4d.LIGHTTAG_POWER, self._floatFunc, modifierFunction=self._multiplyBy, modifierParam=1),
                    XmlLightAttribute("width", c4d.LIGHT_AREADETAILS_SIZEX, self._floatFuncTagParent, vrayAttribute=True, modifierFunction=self._convertAreaLightSize),
                    XmlLightAttribute("height", c4d.LIGHT_AREADETAILS_SIZEY, self._floatFuncTagParent, vrayAttribute=True, modifierFunction=self._convertAreaLightSize),
                    XmlLightAttribute("height", c4d.LIGHT_AREADETAILS_SIZEZ, self._floatFuncTagParent, vrayAttribute=True, modifierFunction=self._convertAreaLightSize),
                    XmlLightAttribute("depth", c4d.LIGHT_AREADETAILS_SIZEZ, self._floatFuncTagParent, vrayAttribute=True, modifierFunction=self._convertAreaLightSize),
                                        ]
        
        if self._vrayLights:
            #----- Vray properties
            self._vrayLightAttributes = [
                XmlLightAttribute("on", c4d.ID_BASEOBJECT_GENERATOR_FLAG, self._boolFuncTagParent, vrayAttribute=True),
                XmlLightAttribute("on", c4d.LIGHT_PHOTOMETRIC_UNITS, self._boolFuncTagParent, vrayAttribute=True),
                XmlLightAttribute("type", c4d.VRAYLIGHTTAG_COMMON_LIGHTTYPE, self._lightStrTypeFunc, vrayAttribute=True),
                XmlLightAttribute("enabled", c4d.VRAYLIGHTTAG_SUN_ON, self._boolFunc, vrayAttribute=True),
                XmlLightAttribute("enabled", c4d.VRAYLIGHTTAG_IES_ON, self._boolFunc, vrayAttribute=True),
                XmlLightAttribute("color", c4d.LIGHT_COLOR, self._colorFuncTagParent, vrayAttribute=True),
                XmlLightAttribute("affect_diffuse", c4d.VRAYLIGHTTAG_COMMON_AFFECTDIFF, self._boolFunc, vrayAttribute=True),
                XmlLightAttribute("affect_specular", c4d.VRAYLIGHTTAG_COMMON_AFFECTSPEC, self._boolFunc, vrayAttribute=True),
                XmlLightAttribute("affect_reflections", c4d.VRAYLIGHTTAG_AREA_AFFECTREFL, self._boolFunc, vrayAttribute=True),
                XmlLightAttribute("invisible", c4d.VRAYLIGHTTAG_AREA_INVISIBLE, self._boolFunc, vrayAttribute=True),
                XmlLightAttribute("sun_invisible", c4d.VRAYLIGHTTAG_SUN_INVISIBLE, self._boolFunc, vrayAttribute=True),
                XmlLightAttribute("cast_shadow", c4d.VRAYLIGHTTAG_SUN_ATMOSHADOWS, self._boolFunc, vrayAttribute=True),
                XmlLightAttribute("turbidity", c4d.VRAYLIGHTTAG_SUN_TURB, self._floatFunc, vrayAttribute=True),
                XmlLightAttribute("ies_file", c4d.VRAYLIGHTTAG_IES_FILE, self._pathFunc, vrayAttribute=True),
                XmlLightAttribute("ozone", c4d.VRAYLIGHTTAG_SUN_OZONE, self._floatFunc, vrayAttribute=True),
                XmlLightAttribute("size_multiplier", c4d.VRAYLIGHTTAG_SUN_SIZEMUL, self._floatFunc, vrayAttribute=True),
                XmlLightAttribute("intensity_multiplier", c4d.VRAYLIGHTTAG_SUN_SIZEMUL, self._sunIntensityFunc, vrayAttribute=True),
                XmlLightAttribute("filter_color", c4d.VRAYLIGHTTAG_SUN_FILTERCLR, self._colorFunc, vrayAttribute=True),
                XmlLightAttribute("photon_emit_radius", c4d.VRAYLIGHTTAG_SUN_PHOTONRAD, self._floatFunc, vrayAttribute=True, modifierFunction=self._maxGenericToCmFloat),
                XmlLightAttribute("sky_model", c4d.VRAYLIGHTTAG_SUN_SKYMODELS, self._intFunc, vrayAttribute=True),
                XmlLightAttribute("multiplier", c4d.VRAYLIGHTTAG_COMMON_INTENSITY, self._floatFunc, vrayAttribute=True),
                XmlLightAttribute("power", c4d.VRAYLIGHTTAG_IES_FILTER_MULT, self._floatFunc, vrayAttribute=True),
                XmlLightAttribute("multiplier", c4d.LIGHT_PHOTOMETRIC_INTENSITY, self._setLightIntensityUnit, vrayAttribute=True),
                XmlLightAttribute("units", c4d.VRAYLIGHTTAG_COMMON_UNITS, self._vrayLightUnitConversion, vrayAttribute=True),
                XmlLightAttribute("v_shadow", c4d.VRAYLIGHTTAG_COMMON_SHDON, self._boolFunc, vrayAttribute=True),
                XmlLightAttribute("shadow_bias", c4d.VRAYLIGHTTAG_COMMON_SUNSHDBIAS, self._floatFunc, vrayAttribute=True),
                XmlLightAttribute("shadow_bias", c4d.VRAYLIGHTTAG_COMMON_SHDBIAS, self._floatFunc, vrayAttribute=True),
                XmlLightAttribute("shadow_subdivs", c4d.VRAYLIGHTTAG_COMMON_SHDSUBDIVS, self._intFunc, vrayAttribute=True),
                XmlLightAttribute("shadow_subdivs", c4d.VRAYLIGHTTAG_AREA_SUBDIVS, self._intFunc, vrayAttribute=True),
                XmlLightAttribute("shadow_radius", c4d.VRAYLIGHTTAG_COMMON_SHDRADIUS, self._floatFunc, vrayAttribute=True),
                XmlLightAttribute("v_type", c4d.VRAYLIGHTTAG_COMMON_LIGHTTYPE, self._lightStrTypeFunc, vrayAttribute=True),
                XmlLightAttribute("v_area_type", c4d.VRAYLIGHTTAG_AREA_TYPE, self._lightStrTypeFunc, vrayAttribute=True),
                XmlLightAttribute("width", c4d.LIGHT_AREADETAILS_SIZEX, self._floatFuncTagParent, vrayAttribute=True, modifierFunction=self._convertAreaLightSize),
                XmlLightAttribute("height", c4d.LIGHT_AREADETAILS_SIZEY, self._floatFuncTagParent, vrayAttribute=True, modifierFunction=self._convertAreaLightSize),
                XmlLightAttribute("height", c4d.LIGHT_AREADETAILS_SIZEZ, self._floatFuncTagParent, vrayAttribute=True, modifierFunction=self._convertAreaLightSize),
                XmlLightAttribute("depth", c4d.LIGHT_AREADETAILS_SIZEZ, self._floatFuncTagParent, vrayAttribute=True, modifierFunction=self._convertAreaLightSize),
                XmlLightAttribute("radius", c4d.VRAYLIGHTTAG_AREA_RADIUS, self._floatFunc, vrayAttribute=True),
                XmlLightAttribute("skylightPortal", c4d.VRAYLIGHTTAG_AREA_PORTAL, self._vrayPortalLightFunc, vrayAttribute=True),
                XmlLightAttribute("simplePortal", c4d.VRAYLIGHTTAG_AREA_PORTAL, self._vrayPortalLightFunc, vrayAttribute=True),
                
                

                XmlLightAttribute("ies_intensity_value", c4d.VRAYLIGHTTAG_IES_FILTER_MULT, self._floatFunc, modifierFunction=self._multiplyBy,modifierParam=1.398, vrayAttribute=True),
                XmlLightAttribute("ies_filename", c4d.VRAYLIGHTTAG_IES_FILE, self._stdIESFilenameAndEnable, vrayAttribute=True),
                XmlLightAttribute("ies_filename", c4d.VRAYLIGHTTAG_IES_FILE, self._pathFunc, vrayAttribute=True),
                    ]
        
            self._vrayLightStr =    {
                # ----- vray_str : (vray_desc, std_str)
                ("type", "ies") : (c4d.VRAYLIGHTTAG_COMMON_LIGHTTYPE_0, ("type", "ies")),
                ("type", "VRayIES") : (c4d.VRAYLIGHTTAG_COMMON_LIGHTTYPE_0, ("type", "ies")),
                ("v_type", "sun") : (c4d.VRAYLIGHTTAG_COMMON_LIGHTTYPE_2, ("type", "infinite")),
                ("v_type", "omni") : (c4d.VRAYLIGHTTAG_COMMON_LIGHTTYPE_0, ("type", "omni")),
                ("v_type", "spot") : (c4d.VRAYLIGHTTAG_COMMON_LIGHTTYPE_1, ("type", "spot")),
                ("v_type", "infinite") : (c4d.VRAYLIGHTTAG_COMMON_LIGHTTYPE_2, ("type", "infinite")),
                ("v_type", "area") : (c4d.VRAYLIGHTTAG_COMMON_LIGHTTYPE_3, ("type", "area")),
                ("v_type", "parallel") : (c4d.VRAYLIGHTTAG_COMMON_LIGHTTYPE_4, ("type", "parallel")),
                ("v_type", "ambient") : (c4d.VRAYLIGHTTAG_COMMON_LIGHTTYPE_5, ("type", "ambient")),
                ("v_area_type", "plane") : (c4d.VRAYLIGHTTAG_AREA_TYPE_0, ("area_type", "plane")),
                ("v_area_type", "sphere") : (c4d.VRAYLIGHTTAG_AREA_TYPE_1,("area_type", "sphere")),
                ("v_area_type", "dome") : (c4d.VRAYLIGHTTAG_AREA_TYPE_2,("area_type", "hemisphere")),
                ("v_area_type", "mesh") : (c4d.VRAYLIGHTTAG_AREA_TYPE_3,("area_type", "mesh")),
                ("v_shadow", "true") : (c4d.VRAYLIGHTTAG_COMMON_SHDON, ("shadow", "area")),
                ("v_shadow", "false") : (c4d.VRAYLIGHTTAG_COMMON_SHDON, ("shadow", "none"))
                                    }
        
        if not self._vrayLights:
        
            #----- Vray -> standard
            self._lightAttributes[len(self._lightAttributes):] =    [
                #XmlLightAttribute("multiplier", c4d.LIGHT_BRIGHTNESS, self._floatFuncDivDiez),
                #XmlLightAttribute("multiplier", c4d.LIGHT_BRIGHTNESS, self._floatFunc,modifierFunction=self._multiplyBy,modifierParam=0.3),
                #XmlLightAttribute("units", c4d.LIGHT_BRIGHTNESS, self._vrayLightUnitConversion),
                XmlLightAttribute("v_shadow", c4d.LIGHT_SHADOWTYPE, self._comboBoxFunc, vrayConvert=self._vrayLightConvert),
                XmlLightAttribute("v_type", c4d.LIGHT_TYPE, self._comboBoxFunc, vrayConvert=self._vrayLightConvert),
                XmlLightAttribute("v_area_type", c4d.LIGHT_AREADETAILS_SHAPE, self._comboBoxFunc, vrayConvert=self._vrayLightConvert),
                XmlLightAttribute("skylightPortal", c4d.ID_BASEOBJECT_GENERATOR_FLAG, self._invertBool, self._invertBool),
                                                                    ]
            
            self._vrayLightConvStr =    {
                # ----- vray_str : (vray_desc, std_str)
                ("type", "ies") : ("type", "ies"),
                ("type", "VRayIES") : ("type", "ies"),
                ("v_type", "sun") : ("type", "infinite"),
                ("v_type", "omni") : ("type", "omni"),
                ("v_type", "spot") : ("type", "spot"),
                ("v_type", "infinite") : ("type", "infinite"),
                ("v_type", "area") : ("type", "area"),
                ("v_type", "parallel") : ("type", "parallel"),
                ("v_type", "ambient") : ("type", "ambient"),
                ("v_area_type", "plane") : ("area_type", "plane"),
                ("v_area_type", "sphere") : ("area_type", "sphere"),
                ("v_area_type", "dome") : ("area_type", "hemisphere"),
                ("v_area_type", "mesh") : ("area_type", "mesh"),
                ("v_shadow", "true") : ("shadow", "area"),
                ("v_shadow", "false") : ("shadow", "none")
                                    }
    
    def _initCamArray(self):
        """Store each recognized camera attribute in xml.
        """
        self._camStr = {
            #----- std_str : std_desc
                       }
        self._camAttributes = [
            XmlCamAttribute("active", False, self._setActiveCam),
            XmlCamAttribute("filmgate", c4d.CAMERAOBJECT_APERTURE, self._floatFunc),
            XmlCamAttribute("lens", c4d.CAMERA_FOCUS, self._floatFunc),
            XmlCamAttribute("fov", c4d.CAMERAOBJECT_FOV, self._floatFunc,modifierFunction=self._angleToRad),
            XmlCamAttribute("focallength", c4d.CAMERA_FOCUS, self._floatFunc),
            #XmlCamAttribute("fov_amount", c4d.CAMERAOBJECT_FOV, self._floatFunc,modifierFunction=self._angleToRad),
                              ]
        if self._vrayCameras:
            
            #----- Vray properties
            self._camAttributes[len(self._camAttributes):] = [
                XmlCamAttribute("vignetting", c4d.VRAYPHYSICALCAMERATAG_SHUTTERPRIORITY, self._boolFunc),
                XmlCamAttribute("vignetting_amount", c4d.VRAYPHYSICALCAMERATAG_VIGNETTING, self._floatFunc),
                XmlCamAttribute("f-number", c4d.VRAYPHYSICALCAMERATAG_FSTOP, self._floatFunc),
                XmlCamAttribute("shutter_speed", c4d.VRAYPHYSICALCAMERATAG_SHUTTERSPEED, self._floatFunc),
                XmlCamAttribute("ISO", c4d.VRAYPHYSICALCAMERATAG_ISO, self._floatFunc),
                                                             ]
                
            self._vrayCamStr =    {
                # ----- vray_str : (vray_desc, std_str)
                                  }
        else:
			#----- Vray -> standard
			self._camAttributes[len(self._camAttributes):] =    [
                XmlCamAttribute("f-number", c4d.CAMERAOBJECT_FNUMBER_VALUE, self._floatFunc),
                XmlCamAttribute("shutter_speed", c4d.CAMERAOBJECT_SHUTTER_SPEED_VALUE, self._stdShutterFunc),
                XmlCamAttribute("ISO", c4d.CAMERAOBJECT_ISO_VALUE, self._floatFunc),
                                                                ]
    
    def _initShaderArray(self):
        
        if self._vrayLights or self._vrayMaterials:
            
            ##########################################################################################################
            ##### VRAY SHADER Types ##################################################################################
            ##########################################################################################################
            
            self._shaderTypes = [
                XmlShaderTypeAttribute("bitmap", 10, vrayAttribute=True),                   #Vray Bitmap
                XmlShaderTypeAttribute("Bitmaptexture", 10, vrayAttribute=True),            #Vray Bitmap
                XmlShaderTypeAttribute("VRayHDRI", 10, vrayAttribute=True),                 #Vray Bitmap
                XmlShaderTypeAttribute("Cellular", 48, vrayAttribute=True),                 #Vray Cellular
                XmlShaderTypeAttribute("FallOff", 27, vrayAttribute=True),                  #Vray Falloff
                XmlShaderTypeAttribute("VRayDirt", 45, vrayAttribute=True),                 #Vray Dirt
                XmlShaderTypeAttribute("Color_Correction", 7, vrayAttribute=True),          #Vray CC
                XmlShaderTypeAttribute("Mix", 29, vrayAttribute=True),                      #Vray Mix
                XmlShaderTypeAttribute("CompositeTexturemap", 29, vrayAttribute=True),      #Vray Mix
                XmlShaderTypeAttribute("Noise", 28, vrayAttribute=True),                    #Vray NoiseMax
                XmlShaderTypeAttribute("Gradient_Ramp", 37, vrayAttribute=True),            #Vray GradRamp
                XmlShaderTypeAttribute("Normal_Bump", 10, vrayAttribute=True),              #Vray Bitmap
                XmlShaderTypeAttribute("VRayColor", 52, vrayAttribute=True),                #Vray Color
                XmlShaderTypeAttribute("output", 7, vrayAttribute=True),                    #Vray CC
                XmlShaderTypeAttribute("VRayMap", "", vrayAttribute=True),                  #For Max ReflectRefract Shader
                XmlShaderTypeAttribute("VRayNormalMap", "60", vrayAttribute=True),          #Vray NormalMap
                XmlShaderTypeAttribute("Speckle", "33", vrayAttribute=True),                #Vray Speckle
                                                         ]
            
            ##########################################################################################################
            ##### VRAY SHADER Attributes #############################################################################
            ##########################################################################################################
            
            self._vrayShaderAttributes = [
                #Bitmaptexture
                #XmlShaderAttribute("filename", c4d.BITMAPSHADER_FILENAME, self._bitmapShaderFunc, vrayAttribute=True),
                #EnvBitmap
                #XmlShaderAttribute("Path", c4d.BITMAPSHADER_FILENAME, self._bitmapShaderFunc, vrayAttribute=True),
                #Bitmaptexture
                XmlShaderAttribute("filename", 4999, self._vrayShaderPath, vrayAttribute=True),
                #EnvBitmap
                XmlShaderAttribute("Path", 4999, self._vrayShaderPath, vrayAttribute=True),
                #OUTPUT -> C4D Filter
                XmlShaderAttribute("output_map", 76821548, self._bitmapFunc, vrayAttribute=False),
                #StdNormalBump->VRayMix
                XmlShaderAttribute("normal_normal_map", 114886856, self._bitmapFunc),
                XmlShaderAttribute("normal_bump_map", 114886956, self._bitmapFunc),
                #StdMix -> VRayMix
                XmlShaderAttribute("mix_mixAmount", 114797471, self._percToColor),
                XmlShaderAttribute("mix_color1", 114797469, self._colorFunc),
                XmlShaderAttribute("mix_color2", 114797470, self._colorFunc),
                #XmlShaderAttribute("mix_maskEnabled", c4d.SLA_FUSION_USE_MASK, self._boolFunc),
                XmlShaderAttribute("mix_map1", 114886856, self._bitmapFunc),
                XmlShaderAttribute("mix_map2", 114886956, self._bitmapFunc),
                XmlShaderAttribute("mix_mask", 114887056, self._bitmapFunc),
                #StdGradRamp -> VRayGradient
                #XmlShaderAttribute("ramp_size", c4d.SLA_GRADIENT_SCALE, self._floatFunc, modifierFunction=self._divideBy, modifierParam=10),
                #XmlShaderAttribute("ramp_amount", c4d.SLA_GRADIENT_TURBULENCE, self._floatFunc),
                #XmlShaderAttribute("ramp_levels", c4d.SLA_GRADIENT_OCTAVES, self._floatFunc),
                XmlShaderAttribute("ramp_gradientType", 264317982, self._shaderStrTypeFunc),
                #XmlShaderAttribute("ramp_noiseType", c4d.SLA_GRADIENT_SCALE, self._gradShaderStrTypeFunc),
                #XmlShaderAttribute("ramp_Flag_Color", c4d.SLA_GRADIENT_SCALE, self._floatFunc),
                #StdNoise -> VRayNoise
                #XmlShaderAttribute("noise_seed", c4d.SLA_NOISE_SEED, self._intFunc),
                XmlShaderAttribute("noisecolor1", 7209825, self._colorFunc),
                XmlShaderAttribute("noisecolor2", 7209826, self._colorFunc),
                XmlShaderAttribute("noise_type", 7209832, self._shaderStrTypeFunc),
                XmlShaderAttribute("noise_size", 7209827, self._floatFunc,modifierFunction=self._divideBy,modifierParam=1),
                XmlShaderAttribute("noise_lowThreshold", 7209830, self._floatFunc),
                XmlShaderAttribute("noise_highThreshold", 7209831, self._floatFunc),
                XmlShaderAttribute("noise_levels", 7209829, self._floatFunc),
                #Speckle -> VRaySpeckle
                XmlShaderAttribute("speckle_size", 244393695, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("speckle_color1", 244393693, self._colorFunc, vrayAttribute=True),
                XmlShaderAttribute("speckle_color2", 244393694, self._colorFunc, vrayAttribute=True),
                XmlShaderAttribute("speckle_map1", 244498564, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("speckle_map2", 244498664, self._bitmapFunc, vrayAttribute=True),
                #VrayNormalMap->VrayNormalMap
                XmlShaderAttribute("vraynormalmap_normal_map", 259396642, self._bitmapFunc),
                #CC -> VRayCC
                XmlShaderAttribute("cc_Color", 76800061, self._colorFunc, vrayAttribute=True),
                XmlShaderAttribute("cc_hueShift", 76800064, self._hueShiftFunc, vrayAttribute=True),
                XmlShaderAttribute("cc_saturation", 76800065, self._floatFunc,modifierFunction=self._divideBy,modifierParam=100, vrayAttribute=True),
                XmlShaderAttribute("cc_contrast", 76800063, self._ccContrastFunc, vrayAttribute=True),
                XmlShaderAttribute("cc_gammaRGB", 76800062, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("cc_brightness", 76800066, self._ccLevelFunc, vrayAttribute=True),
                XmlShaderAttribute("cc_map", 76821548, self._bitmapFunc, vrayAttribute=True),
                #Composite -> C4D Fusion
                XmlShaderAttribute("composite_map1", c4d.SLA_FUSION_BLEND_CHANNEL, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_map2", c4d.SLA_FUSION_BLEND_CHANNEL, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_map3", c4d.SLA_FUSION_BLEND_CHANNEL, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_map4", c4d.SLA_FUSION_BLEND_CHANNEL, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mask1", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mask2", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mask3", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mask4", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mask5", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mask6", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mask7", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mask8", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mask9", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mapEnabled1", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mapEnabled2", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mapEnabled3", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mapEnabled4", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mapEnabled5", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mapEnabled6", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mapEnabled7", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mapEnabled8", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_mapEnabled9", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_maskEnabled1", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_maskEnabled2", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_maskEnabled3", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_maskEnabled4", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_maskEnabled5", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_maskEnabled6", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_maskEnabled7", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_maskEnabled8", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_maskEnabled9", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_blendMode1", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_blendMode2", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_blendMode3", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_blendMode4", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_blendMode5", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_blendMode6", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_blendMode7", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_blendMode8", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_blendMode9", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_layerName1", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_layerName2", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_layerName3", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_layerName4", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_dlgOpened1", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_dlgOpened2", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_dlgOpened3", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_dlgOpened4", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_opacity1", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_opacity2", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_opacity3", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_opacity4", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_opacity5", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_opacity6", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_opacity7", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_opacity8", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("composite_opacity9", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                #Composite -> VRayMix
                # XmlShaderAttribute("composite_map1", 114886956, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_map2", 114886956, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_map3", 114886956, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_map4", 114886956, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_map5", 114886956, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_map6", 114886956, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_map7", 114886956, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_map8", 114886956, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_map9", 114886956, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mask1", 114887056, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mask2", 114887056, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mask3", 114887056, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mask4", 114887056, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mask5", 114887056, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mask6", 114887056, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mask7", 114887056, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mask8", 114887056, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mask9", 114887056, self._bitmapFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mapEnabled1", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mapEnabled2", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mapEnabled3", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mapEnabled4", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mapEnabled5", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mapEnabled6", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mapEnabled7", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mapEnabled8", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_mapEnabled9", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_maskEnabled1", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_maskEnabled2", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_maskEnabled3", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_maskEnabled4", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_maskEnabled5", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_maskEnabled6", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_maskEnabled7", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_maskEnabled8", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_maskEnabled9", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_blendMode1", 72354685, self._shaderStrTypeFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_blendMode2", 72354685, self._shaderStrTypeFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_blendMode3", 72354685, self._shaderStrTypeFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_blendMode4", 72354685, self._shaderStrTypeFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_blendMode5", 72354685, self._shaderStrTypeFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_blendMode6", 72354685, self._shaderStrTypeFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_blendMode7", 72354685, self._shaderStrTypeFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_blendMode8", 72354685, self._shaderStrTypeFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_blendMode9", 72354685, self._shaderStrTypeFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_layerName1", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_layerName2", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_layerName3", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_layerName4", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_layerName5", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_layerName6", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_layerName7", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_layerName8", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_layerName9", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_dlgOpened1", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_dlgOpened2", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_dlgOpened3", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_dlgOpened4", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=True),
                # XmlShaderAttribute("composite_opacity1", 114797471, self._percToColor, vrayAttribute=True),
                # XmlShaderAttribute("composite_opacity2", 114797471, self._percToColor, vrayAttribute=True),
                # XmlShaderAttribute("composite_opacity3", 114797471, self._percToColor, vrayAttribute=True),
                # XmlShaderAttribute("composite_opacity4", 114797471, self._percToColor, vrayAttribute=True),
                # XmlShaderAttribute("composite_opacity5", 114797471, self._percToColor, vrayAttribute=True),
                # XmlShaderAttribute("composite_opacity6", 114797471, self._percToColor, vrayAttribute=True),
                # XmlShaderAttribute("composite_opacity7", 114797471, self._percToColor, vrayAttribute=True),
                # XmlShaderAttribute("composite_opacity8", 114797471, self._percToColor, vrayAttribute=True),
                # XmlShaderAttribute("composite_opacity9", 114797471, self._percToColor, vrayAttribute=True),
                #Cellular -> VRay Cellular
                XmlShaderAttribute("cell_Color", 10355703, self._colorFunc, vrayAttribute=True),
                XmlShaderAttribute("cell_divColor1", 10355704, self._colorFunc, vrayAttribute=True),
                XmlShaderAttribute("cell_divColor2", 10355705, self._colorFunc, vrayAttribute=True),
                XmlShaderAttribute("cell_type", 10355709, self._shaderStrTypeFunc, vrayAttribute=True),
                XmlShaderAttribute("cell_size", 10355706, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("cell_spread", 10355707, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("cell_fractal", 10355713, self._boolFunc, vrayAttribute=True),
                XmlShaderAttribute("cell_iteration", 10355714, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("cell_roughness", 10355715, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("cell_lowThreshold", 10355710, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("cell_midhreshold", 10355711, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("cell_highThreshold", 10355712, self._floatFunc, vrayAttribute=True),
                #Falloff -> VRay Falloff
                XmlShaderAttribute("falloffcolor1", 223109425, self._colorFunc, vrayAttribute=True),
                XmlShaderAttribute("falloffcolor2", 223109426, self._colorFunc, vrayAttribute=True),
                XmlShaderAttribute("falloff_map1", 223192612, self._colorFunc, vrayAttribute=True),
                XmlShaderAttribute("falloff_map2", 223192712, self._colorFunc, vrayAttribute=True),
                XmlShaderAttribute("falloff_direction", 223109428, self._shaderStrTypeFunc, vrayAttribute=True),
                XmlShaderAttribute("falloff_nearDistance", 223109431, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("falloff_farDistance", 223109432, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("falloff_extrapolate", 223109430, self._boolFunc, vrayAttribute=True),
                XmlShaderAttribute("fallof_type", 223109427, self._fallshaderStrTypeFunc, vrayAttribute=True),
                XmlShaderAttribute("falloff_IORvalue", 223109429, self._floatFunc, vrayAttribute=True),
                #VRayDirt -> VRayDirt
                XmlShaderAttribute("vrdirt_occludedColor", 220264368, self._colorFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_unoccludedColor", 220264367, self._colorFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_mode", 220264385, self._shaderStrTypeFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_radius", 220264369, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_distribution", 220264370, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_falloff", 220264371, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_subdivs", 220264372, self._intFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_bias", 220264375, self._dirtBiasFunc, vrayAttribute=True),
                #????XmlShaderAttribute("vrdirt_affectAlpha", 223109430, self._boolFunc, vrayAttribute=True),????
                XmlShaderAttribute("vrdirt_ignoreForGI", 220264376, self._boolFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_considerSameObjectOnly", 220264377, self._boolFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_invertNormal", 220264378, self._boolFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_workWithTransparency", 220264380, self._boolFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_environmentOcclusion", 220264386, self._boolFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_affectReflectionElements", 220264387, self._boolFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_reflectionGlossiness", 220264388, self._floatFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_occluded_color", 220401867, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_unoccluded_color", 220401767, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_reflection_glossiness", 220403867, self._bitmapFunc, vrayAttribute=True),
                XmlShaderAttribute("vrdirt_texmap_radius", 220401967, self._bitmapFunc, vrayAttribute=True),
                #VRayColor -> VRayColor
                XmlShaderAttribute("vrcolor_color", 67565718, self._colorFunc, vrayAttribute=True),
                                         ]
            
            ##########################################################################################################
            ##### VRAY SHADER Strings ################################################################################
            ##########################################################################################################
            
            self._shaderStr = [
                #Composite BlendingModes
                XmlShaderTypeAttribute("Normal", 2001),
                XmlShaderTypeAttribute("Multiply", 2019),
                XmlShaderTypeAttribute("Screen", 2002),
                XmlShaderTypeAttribute("Overlay", 2003),
                XmlShaderTypeAttribute("Addition", 2010),
                XmlShaderTypeAttribute("Subtract", 2011),
                XmlShaderTypeAttribute("Difference", 2012),
                XmlShaderTypeAttribute("Lighten", 2009),
                XmlShaderTypeAttribute("Darken", 2008),
                XmlShaderTypeAttribute("Saturation", 2015),
                XmlShaderTypeAttribute("Average", 2003), #Overlay
                XmlShaderTypeAttribute("Spotlight", 2004), #Hard Light
                XmlShaderTypeAttribute("Spotlight Blend", 2005), #Soft Light
                XmlShaderTypeAttribute("Soft Light", 2005),
                XmlShaderTypeAttribute("Hard light", 2004),
                XmlShaderTypeAttribute("Pin Light", 2004),
                XmlShaderTypeAttribute("Color Burn", 2007),
                XmlShaderTypeAttribute("Linear Burn", 2007),
                XmlShaderTypeAttribute("Color Dodge", 2006),
                XmlShaderTypeAttribute("Linear Dodge", 2006),
                XmlShaderTypeAttribute("Screen", 2002),
                XmlShaderTypeAttribute("Hard Mix", 2004), #Hard Light
                XmlShaderTypeAttribute("Exclusion", 2013),
                XmlShaderTypeAttribute("Hue", 2014),
                XmlShaderTypeAttribute("Value", 2017), #Luminance
                
                #Composite BlendingModes
                # XmlShaderTypeAttribute("Normal", 0),
                # XmlShaderTypeAttribute("Overlay", 1),
                #-----------------------"In"---------
                #-----------------------"Out"---------
                # XmlShaderTypeAttribute("Addition", 4),
                # XmlShaderTypeAttribute("Subtract", 5),
                # XmlShaderTypeAttribute("Multiply", 6),
                # XmlShaderTypeAttribute("Difference", 7),
                # XmlShaderTypeAttribute("Lighten", 8),
                # XmlShaderTypeAttribute("Darken", 9),
                # XmlShaderTypeAttribute("Saturation", 10),
                # XmlShaderTypeAttribute("Average", 11),
                # XmlShaderTypeAttribute("Spotlight", 12),
                # XmlShaderTypeAttribute("Spotlight Blend", 12),
                # XmlShaderTypeAttribute("Soft Light", 12),
                # XmlShaderTypeAttribute("Hard light", 12),
                # XmlShaderTypeAttribute("Pin Light", 12),
                # XmlShaderTypeAttribute("Color Burn", 6),
                # XmlShaderTypeAttribute("Linear Burn", 6),
                # XmlShaderTypeAttribute("Color Dodge", 6),
                # XmlShaderTypeAttribute("Linear Dodge", 6),
                # XmlShaderTypeAttribute("Screen", 8),
                # XmlShaderTypeAttribute("Hard Mix", 6),
                # XmlShaderTypeAttribute("Exclusion", 7),
                # XmlShaderTypeAttribute("Hue", 10),
                # XmlShaderTypeAttribute("Value", 1),
                
                #Noise Types
                XmlShaderTypeAttribute("Regular", 0),
                XmlShaderTypeAttribute("Fractal", 1),
                XmlShaderTypeAttribute("Turbulence", 2),
                
                #Cellular CellTypes
                XmlShaderTypeAttribute("Circular", 0),
                XmlShaderTypeAttribute("Chips", 1),
                
                #Falloff DirectionTypes
                XmlShaderTypeAttribute("Viewing Direction (Camera Z-Axis)", 0),
                                
                #Gradient Type
                XmlShaderTypeAttribute("4 Corner", 0),
                XmlShaderTypeAttribute("Box", 1),
                XmlShaderTypeAttribute("Diagonal", 2),
                XmlShaderTypeAttribute("Lighting", 3),
                XmlShaderTypeAttribute("Linear", 4),
                XmlShaderTypeAttribute("Mapped", 5),
                XmlShaderTypeAttribute("Normal", 6),
                XmlShaderTypeAttribute("Pong", 7),
                XmlShaderTypeAttribute("Radial", 8),
                XmlShaderTypeAttribute("Spiral", 9),
                XmlShaderTypeAttribute("Sweep", 10),
                XmlShaderTypeAttribute("Tartan", 11),
                
                #Falloff FalloffTypes
                XmlShaderTypeAttribute("Towards/Away", 0),
                XmlShaderTypeAttribute("Perpendicular/Parallel", 1),
                XmlShaderTypeAttribute("Fresnel", 2),
                XmlShaderTypeAttribute("Shadow/Light", 3),
                                                     ]
        
        elif self._usingOctane:
            
            ##########################################################################################################
            ##### OCTANE SHADER Types ################################################################################
            ##########################################################################################################
            
            self._shaderTypes = [
                XmlShaderTypeAttribute("bitmap", 1029508, vrayAttribute=False),         #C4D Bitmap
                XmlShaderTypeAttribute("Bitmaptexture", 1029508, vrayAttribute=False),  #C4D Bitmap
                XmlShaderTypeAttribute("VRayHDRI", c4d.Xbitmap, vrayAttribute=False),       #C4D Bitmap
                                ]
            
            ##########################################################################################################
            ##### OCTANE SHADER Attributes ###########################################################################
            ##########################################################################################################
            
            self._octShaderAttributes = [
                #Bitmaptexture
                XmlShaderAttribute("filename", c4d.IMAGETEXTURE_FILE, self._bitmapShaderFunc),
                
                #EnvBitmap
                XmlShaderAttribute("Path", c4d.BITMAPSHADER_FILENAME, self._bitmapShaderFunc),
                XmlShaderAttribute("HDRIMapName", c4d.BITMAPSHADER_FILENAME, self._bitmapShaderFunc),
                                        ]
            
            ##########################################################################################################
            ##### OCTANE SHADER Strings ##############################################################################
            ##########################################################################################################
            
            self._shaderStr = [
                #
                              ]
            
        else:
            
            ##########################################################################################################
            ##### STD SHADER Types ###################################################################################
            ##########################################################################################################
            
            self._shaderTypes = [
                XmlShaderTypeAttribute("bitmap", c4d.Xbitmap, vrayAttribute=False),         #C4D Bitmap
                XmlShaderTypeAttribute("Bitmaptexture", c4d.Xbitmap, vrayAttribute=False),  #C4D Bitmap
                XmlShaderTypeAttribute("VRayHDRI", c4d.Xbitmap, vrayAttribute=False),       #C4D Bitmap
                XmlShaderTypeAttribute("Mix", 1011109, vrayAttribute=False),                #C4D Fusion
                XmlShaderTypeAttribute("Cellular", 1011116, vrayAttribute=False),           #C4D Noise
                XmlShaderTypeAttribute("FallOff", 1011109, vrayAttribute=False),            #C4D Fusion
                XmlShaderTypeAttribute("VRayDirt", 1001191, vrayAttribute=False),           #C4D AO
                XmlShaderTypeAttribute("Color_Correction", 1011128, vrayAttribute=False),   #C4D Filter
                XmlShaderTypeAttribute("CompositeTexturemap", 1011128, vrayAttribute=False),#C4D Fusion
                XmlShaderTypeAttribute("Noise", c4d.Xnoise, vrayAttribute=False),           #C4D Noise
                XmlShaderTypeAttribute("Gradient_Ramp", 1011100, vrayAttribute=False),      #C4D Gradient
                XmlShaderTypeAttribute("Normal_Bump", 1011109, vrayAttribute=False),        #C4D Fusion
                XmlShaderTypeAttribute("VRayColor", 5832, vrayAttribute=True),                #Vray Color
                XmlShaderTypeAttribute("output", 1011128, vrayAttribute=False),             #C4D Filter
                XmlShaderTypeAttribute("VRayMap", "", vrayAttribute=False),                 #Sets Parent Material Manually
                                                         ]
            
            ##########################################################################################################
            ##### STD SHADER Attributes ##############################################################################
            ##########################################################################################################
            
            self._shaderAttributes =     [
                #Bitmaptexture
                XmlShaderAttribute("filename", c4d.BITMAPSHADER_FILENAME, self._bitmapShaderFunc),
                #StdNormalBump->C4D Fusion
                XmlShaderAttribute("normal_normal_map", c4d.SLA_FUSION_BASE_CHANNEL, self._bitmapFunc),
                XmlShaderAttribute("normal_bump_map", c4d.SLA_FUSION_BLEND_CHANNEL, self._bitmapFunc),
                #StdMix->C4D Fusion
                XmlShaderAttribute("mix_mixAmount", c4d.SLA_FUSION_BLEND, self._floatFunc),
                XmlShaderAttribute("mix_color1", c4d.SLA_FUSION_BASE_CHANNEL, self._colorToColorShaderFunc),
                XmlShaderAttribute("mix_color2", c4d.SLA_FUSION_BLEND_CHANNEL, self._colorToColorShaderFunc),
                XmlShaderAttribute("mix_maskEnabled", c4d.SLA_FUSION_USE_MASK, self._boolFunc),
                XmlShaderAttribute("mix_map1", c4d.SLA_FUSION_BASE_CHANNEL, self._bitmapFunc),
                XmlShaderAttribute("mix_map2", c4d.SLA_FUSION_BLEND_CHANNEL, self._bitmapFunc),
                XmlShaderAttribute("mix_mask", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc),
                #StdGradRamp->C4D Gradient
                XmlShaderAttribute("ramp_size", c4d.SLA_GRADIENT_SCALE, self._floatFunc, modifierFunction=self._divideBy, modifierParam=10),
                XmlShaderAttribute("ramp_amount", c4d.SLA_GRADIENT_TURBULENCE, self._floatFunc),
                XmlShaderAttribute("ramp_levels", c4d.SLA_GRADIENT_OCTAVES, self._floatFunc),
                XmlShaderAttribute("ramp_gradientType", c4d.SLA_GRADIENT_TYPE, self._shaderStrTypeFunc),
                XmlShaderAttribute("ramp_noiseType", c4d.SLA_GRADIENT_SCALE, self._gradShaderStrTypeFunc),
                XmlShaderAttribute("ramp_Flag_Color", c4d.SLA_GRADIENT_SCALE, self._floatFunc),
                #StdNoise->C4D Noise
                XmlShaderAttribute("noise_seed", c4d.SLA_NOISE_SEED, self._intFunc),
                XmlShaderAttribute("noisecolor1", c4d.SLA_NOISE_COLOR1, self._colorFunc),
                XmlShaderAttribute("noisecolor2", c4d.SLA_NOISE_COLOR2, self._colorFunc),
                XmlShaderAttribute("noise_type", c4d.SLA_NOISE_NOISE, self._shaderStrTypeFunc),
                XmlShaderAttribute("noise_size", c4d.SLA_NOISE_GLOBAL_SCALE, self._floatFunc,modifierFunction=self._divideBy,modifierParam=10),
                XmlShaderAttribute("noise_lowThreshold", c4d.SLA_NOISE_LOW_CLIP, self._floatFunc),
                XmlShaderAttribute("noise_highThreshold", c4d.SLA_NOISE_HIGH_CLIP, self._floatFunc),
                XmlShaderAttribute("noise_levels", c4d.SLA_NOISE_OCTAVES, self._floatFunc),
                #Cellular -> C4D Noise
                XmlShaderAttribute("cell_Color", c4d.SLA_NOISE_COLOR1, self._colorFunc, vrayAttribute=True),
                XmlShaderAttribute("cell_divColor1", c4d.SLA_NOISE_COLOR1, self._cellColorFunc, vrayAttribute=True),
                XmlShaderAttribute("cell_divColor2", c4d.SLA_NOISE_COLOR2, self._colorFunc, vrayAttribute=True),
                XmlShaderAttribute("cell_size", c4d.SLA_NOISE_GLOBAL_SCALE, self._floatFunc, modifierFunction=self._divideBy, modifierParam=10,vrayAttribute=True),
                XmlShaderAttribute("cell_type", c4d.SLA_NOISE_SEED, self._cellNoiseClampFunc, vrayAttribute=True),
                #Falloff -> C4D Fusion (with Fresnel Mask)
                XmlShaderAttribute("falloffcolor1", c4d.SLA_FUSION_BASE_CHANNEL, self._fusionFalloffFunc, modifierFunction=self._colorToColorShaderFunc, vrayAttribute=False),
                XmlShaderAttribute("falloffcolor2", c4d.SLA_FUSION_BLEND_CHANNEL, self._fusionFalloffFunc, modifierFunction=self._colorToColorShaderFunc, vrayAttribute=False),
                XmlShaderAttribute("falloff_map1", c4d.SLA_FUSION_BASE_CHANNEL, self._fusionFalloffFunc, modifierFunction=self._bitmapShaderFunc, vrayAttribute=False),
                XmlShaderAttribute("falloff_map2", c4d.SLA_FUSION_BLEND_CHANNEL, self._fusionFalloffFunc, modifierFunction=self._bitmapShaderFunc, vrayAttribute=False),
                XmlShaderAttribute("fallof_type", c4d.SLA_FRESNEL_PHY_ENABLE, self._fusionFalloffFunc, modifierFunction=self._shaderStrTypeFunc, vrayAttribute=False),
                XmlShaderAttribute("falloff_mtlIOROverride", c4d.SLA_FRESNEL_PHY_ENABLE, self._fusionFalloffFunc, modifierFunction=self._boolFunc, vrayAttribute=True),
                XmlShaderAttribute("falloff_ior", c4d.SLA_FRESNEL_PHY_IOR, self._fusionFalloffFunc, modifierFunction=self._floatFunc, vrayAttribute=False),
                #VRayDirt -> C4D AO
                XmlShaderAttribute("vrdirt_occludedColor", 12345, self._aoGradFunc, vrayAttribute=False),
                XmlShaderAttribute("vrdirt_unoccludedColor", 12345, self._aoGradFunc, vrayAttribute=False),
                XmlShaderAttribute("vrdirt_considerSameObjectOnly", c4d.AMBIENTOCCLUSIONSHADER_SELFTEST, self._boolFunc, vrayAttribute=False),
                XmlShaderAttribute("vrdirt_workWithTransparency", c4d.AMBIENTOCCLUSIONSHADER_TRANSPARENCY, self._boolFunc, vrayAttribute=False),
                #Speckle -> C4D Noise
                XmlShaderAttribute("speckle_size", c4d.SLA_NOISE_GLOBAL_SCALE, self._fusionSpeckleFunc, vrayAttribute=False),
                XmlShaderAttribute("speckle_color1", c4d.SLA_FUSION_BASE_CHANNEL, self._fusionSpeckleFunc, vrayAttribute=False),
                XmlShaderAttribute("speckle_color2", c4d.SLA_FUSION_BLEND_CHANNEL, self._fusionSpeckleFunc, vrayAttribute=False),
                XmlShaderAttribute("speckle_map1", c4d.SLA_FUSION_BASE_CHANNEL, self._fusionSpeckleFunc, vrayAttribute=False),
                XmlShaderAttribute("speckle_map2", c4d.SLA_FUSION_BLEND_CHANNEL, self._fusionSpeckleFunc, vrayAttribute=False),
                #CC -> C4D Filter
                XmlShaderAttribute("cc_Color", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=False),
                XmlShaderAttribute("cc_hueShift", c4d.SLA_FILTER_HUE, self._hueShiftFunc, vrayAttribute=False),
                XmlShaderAttribute("cc_saturation", c4d.SLA_FILTER_SATURATION, self._floatFunc,modifierFunction=self._divideBy,modifierParam=100, vrayAttribute=False),
                XmlShaderAttribute("cc_contrast", c4d.SLA_FILTER_CONTRAST, self._floatFunc,modifierFunction=self._divideBy,modifierParam=100, vrayAttribute=False),
                XmlShaderAttribute("cc_gammaRGB", c4d.SLA_FILTER_GAMMA, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("cc_brightness", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc,modifierFunction=self._divideBy,modifierParam=100, vrayAttribute=False),
                XmlShaderAttribute("cc_map", c4d.SLA_FILTER_TEXTURE, self._bitmapFunc, vrayAttribute=False),
                #OUTPUT -> C4D Filter
                XmlShaderAttribute("output_map", c4d.SLA_FILTER_TEXTURE, self._bitmapFunc, vrayAttribute=False),
                #Composite -> C4D Fusion
                XmlShaderAttribute("composite_map1", c4d.SLA_FUSION_BLEND_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_map2", c4d.SLA_FUSION_BLEND_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_map3", c4d.SLA_FUSION_BLEND_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_map4", c4d.SLA_FUSION_BLEND_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_map5", c4d.SLA_FUSION_BLEND_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_map6", c4d.SLA_FUSION_BLEND_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_map7", c4d.SLA_FUSION_BLEND_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_map8", c4d.SLA_FUSION_BLEND_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_map9", c4d.SLA_FUSION_BLEND_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mask1", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mask2", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mask3", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mask4", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mask5", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mask6", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mask7", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mask8", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mask9", c4d.SLA_FUSION_MASK_CHANNEL, self._bitmapFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mapEnabled1", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mapEnabled2", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mapEnabled3", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mapEnabled4", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mapEnabled5", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mapEnabled6", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mapEnabled7", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mapEnabled8", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_mapEnabled9", c4d.SLA_FILTER_TEXTURE, self._colorToColorShaderFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_maskEnabled1", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_maskEnabled2", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_maskEnabled3", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_maskEnabled4", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_maskEnabled5", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_maskEnabled6", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_maskEnabled7", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_maskEnabled8", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_maskEnabled9", c4d.SLA_FILTER_HUE, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_blendMode1", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_blendMode2", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_blendMode3", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_blendMode4", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_blendMode5", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_blendMode6", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_blendMode7", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_blendMode8", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_blendMode9", c4d.SLA_FUSION_MODE, self._shaderStrTypeFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_layerName1", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_layerName2", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_layerName3", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_layerName4", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_layerName5", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_layerName6", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_layerName7", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_layerName8", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_layerName9", c4d.SLA_FILTER_CONTRAST, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_dlgOpened1", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_dlgOpened2", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_dlgOpened3", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_dlgOpened4", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_dlgOpened5", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_dlgOpened6", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_dlgOpened7", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_dlgOpened8", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_dlgOpened9", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_opacity1", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_opacity2", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_opacity3", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_opacity4", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_opacity5", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_opacity6", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_opacity7", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_opacity8", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                XmlShaderAttribute("composite_opacity9", c4d.SLA_FILTER_BRIGHNESS, self._floatFunc, vrayAttribute=False),
                #VRayColor -> VRayColor
                XmlShaderAttribute("vrcolor_color", c4d.COLORSHADER_COLOR, self._colorFunc, vrayAttribute=True),
                                                                       ]
            
            ##########################################################################################################
            ##### STD SHADER Strings #################################################################################
            ##########################################################################################################
            
            self._shaderStr = [
                #Composite BlendingModes
                XmlShaderTypeAttribute("Normal", 2001),
                XmlShaderTypeAttribute("Multiply", 2019),
                XmlShaderTypeAttribute("Screen", 2002),
                XmlShaderTypeAttribute("Overlay", 2003),
                XmlShaderTypeAttribute("Addition", 2010),
                XmlShaderTypeAttribute("Subtract", 2011),
                XmlShaderTypeAttribute("Difference", 2012),
                XmlShaderTypeAttribute("Lighten", 2009),
                XmlShaderTypeAttribute("Darken", 2008),
                XmlShaderTypeAttribute("Saturation", 2015),
                XmlShaderTypeAttribute("Average", 2003), #Overlay
                XmlShaderTypeAttribute("Spotlight", 2004), #Hard Light
                XmlShaderTypeAttribute("Spotlight Blend", 2005), #Soft Light
                XmlShaderTypeAttribute("Soft Light", 2005),
                XmlShaderTypeAttribute("Hard light", 2004),
                XmlShaderTypeAttribute("Pin Light", 2004),
                XmlShaderTypeAttribute("Color Burn", 2007),
                XmlShaderTypeAttribute("Linear Burn", 2007),
                XmlShaderTypeAttribute("Color Dodge", 2006),
                XmlShaderTypeAttribute("Linear Dodge", 2006),
                XmlShaderTypeAttribute("Screen", 2002),
                XmlShaderTypeAttribute("Hard Mix", 2004), #Hard Light
                XmlShaderTypeAttribute("Exclusion", 2013),
                XmlShaderTypeAttribute("Hue", 2014),
                XmlShaderTypeAttribute("Value", 2017), #Luminance
                #Falloff FalloffTypes
                XmlShaderTypeAttribute("Towards/Away", 0),
                XmlShaderTypeAttribute("Fresnel", 1),
                #Noise Types
                XmlShaderTypeAttribute("Regular", 2013),
                XmlShaderTypeAttribute("Fractal", 2021),
                XmlShaderTypeAttribute("Turbulence", 2012),
                #Gradient Type
                XmlShaderTypeAttribute("4 Corner", 2007),
                XmlShaderTypeAttribute("Box", 2005),
                XmlShaderTypeAttribute("Diagonal", 2002),
                XmlShaderTypeAttribute("Lighting", 2000),
                XmlShaderTypeAttribute("Linear", 2000),
                XmlShaderTypeAttribute("Mapped", 2000),
                XmlShaderTypeAttribute("Normal", 2010),
                XmlShaderTypeAttribute("Pong", 2000),
                XmlShaderTypeAttribute("Radial", 2004),
                XmlShaderTypeAttribute("Spiral", 2003),
                XmlShaderTypeAttribute("Sweep", 2002),
                XmlShaderTypeAttribute("Tartan", 2006),
                              ]
    
    def _initRenderArray(self):
        """Store each recognized render attribute in xml.
        """
        
        self._renderEngines =  {
                #----- str : desc
                 "v_ray" : self.VRAYBRIDGE,
                 "octane" : self.OCTANE
                                }
        self._renderTags = [
                ("savePath", XmlRenderAttribute("name", c4d.RDATA_PATH, self._strFunc)),
                ("projectname", XmlRenderAttribute("name", None, self._docNameFunc)),
                ("renderMode", XmlRenderAttribute("name", None, self._importModeFunc)),
                ("resolution", XmlRenderAttribute("name", (c4d.RDATA_XRES, c4d.RDATA_YRES), self._resolutionFunc)),
                ("renderEngine", XmlRenderAttribute("name", c4d.RDATA_RENDERENGINE, self._renderEngineFunc)),
                ("GammaLut", XmlRenderAttribute("name", c4d.DOCUMENT_LINEARWORKFLOW, self._lwfFunc)),
                ("vray_Environment", XmlRenderAttribute("giShaderType", None, None)),
                ("vray_Environment", XmlRenderAttribute("rrShaderType", None, None)),
                            ]
        
        if self._vrayLights or self._vrayMaterials:
            
            if self._vrayMaterials:
                if (self.VRAY3):
                    self.VRAYBRIDGE_QMCSAMPLER = 3
                    self.VP_VRAYBRIDGE_LOCKTHRESHOLD = 0
                else:
                    self.VRAYBRIDGE_QMCSAMPLER = c4d.VP_VRAYBRIDGE_SAMPLER_ADAPTIVEQMC
                    self.VP_VRAYBRIDGE_LOCKTHRESHOLD = c4d.VP_VRAYBRIDGE_LOCKTHRESHOLD
            
            self._vrayRenderStr = {
                #----- vray_str : (vray_desc)
                ("filterKernel", "Area") : c4d.VP_VRAYBRIDGE_FILTER_AREA,
                ("filterKernel", "Catmull-Rom") : c4d.VP_VRAYBRIDGE_FILTER_CATMULL,
                ("filterKernel", "Blackman") : c4d.VP_VRAYBRIDGE_FILTER_BLACKMAN,
                ("filterKernel", "Mitchell-Netravali") : c4d.VP_VRAYBRIDGE_FILTER_MITCHELL,
                ("filterKernel", "VRayLanczosFilter") : c4d.VP_VRAYBRIDGE_FILTER_LANCZOS,
                ("filterKernel", "VRaySincFilter") : c4d.VP_VRAYBRIDGE_FILTER_SINC,
                ("filterKernel", "VRayBoxFilter") : c4d.VP_VRAYBRIDGE_FILTER_BOX,
                ("filterKernel", "VRayTriangleFilter") : c4d.VP_VRAYBRIDGE_FILTER_TRIANGLE,
                ("imageSamplerType", "Adaptive DMC") : self.VRAYBRIDGE_QMCSAMPLER,
                ("type", "Reinhard") : c4d.VP_VRAYBRIDGE_COLORMAPPING_TYPE_6,
                ("primaryEngine", "Irradiance map") : c4d.VP_VRAYBRIDGE_GIENGINE_IRRADIANCE,
                ("primaryEngine", "Brute force") : c4d.VP_VRAYBRIDGE_GIENGINE_QUASIMC1,
                ("secondaryEngine", "Brute force") : c4d.VP_VRAYBRIDGE_GIENGINE_QUASIMC2,
                ("secondaryEngine", "Light cache") : c4d.VP_VRAYBRIDGE_GIENGINE_LIGHTCACHE2,
                ("Mode", "Single frame") : c4d.VP_VRAYBRIDGE_IRRADMAPMODE_0,
                ("giMapShaderType", "Angular") : c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIMAPTYPE_0,
                ("giMapShaderType", "Cubic") : c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIMAPTYPE_1,
                ("giMapShaderType", "Spherical") : c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIMAPTYPE_2,
                ("giMapShaderType", "MirroredBall") : c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIMAPTYPE_3,
                ("giMapShaderType", "Frontal") : c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIMAPTYPE_4,
                ("rrMapShaderType", "Angular") : c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIMAPTYPE_0,
                ("rrMapShaderType", "Cubic") : c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIMAPTYPE_1,
                ("rrMapShaderType", "Spherical") : c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIMAPTYPE_2,
                ("rrMapShaderType", "MirroredBall") : c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIMAPTYPE_3,
                ("rrMapShaderType", "Frontal") : c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIMAPTYPE_4,
                ("type", "Linear multiply") : 0,
                ("type", "Exponential") : 1,
                ("type", "HSV exponential") : 2,
                ("type", "Intensity exponential") : 3,
                ("type", "Gamma correction") : 4,
                ("type", "Intensity gamma") : 5,
                ("type", "Reinhard") : 6
                                }
            
            self._renderTags[len(self._renderTags):] = [
                ("vray_ImageSampler", XmlRenderAttribute("imageSamplerType", c4d.VP_VRAYBRIDGE_SAMPLER, self._renderStrTypeFunc, vrayAttribute=True)),
                ("vray_ImageSampler", XmlRenderAttribute("filterOn", c4d.VP_VRAYBRIDGE_FILTERON, self._boolFunc, vrayAttribute=True)),
                ("vray_ImageSampler", XmlRenderAttribute("filterKernel", c4d.VP_VRAYBRIDGE_FILTER, self._renderStrTypeFunc, vrayAttribute=True)),
                ("vray_ImageSampler", XmlRenderAttribute("filterSize", c4d.VP_VRAYBRIDGE_FILTERSIZE, self._floatFunc, vrayAttribute=True)),
                ("vray_AdaptiveImageSampler", XmlRenderAttribute("minSubdivs", c4d.VP_VRAYBRIDGE_MINSUBDIV, self._floatFunc, vrayAttribute=True)),
                ("vray_AdaptiveImageSampler", XmlRenderAttribute("maxSubdivs", c4d.VP_VRAYBRIDGE_MAXSUBDIV, self._floatFunc, vrayAttribute=True)),
                ("vray_AdaptiveImageSampler", XmlRenderAttribute("useDMCSamplerThreshold", self.VP_VRAYBRIDGE_LOCKTHRESHOLD, self._boolFunc, vrayAttribute=True)),
                ("vray_AdaptiveImageSampler", XmlRenderAttribute("adaptiveAmount", c4d.VP_VRAYBRIDGE_QMCSAMPLER_ADAPTIVE, self._floatFunc, vrayAttribute=True)),
                ("vray_GlobalDMC", XmlRenderAttribute("timeIndependent", c4d.VP_VRAYBRIDGE_QMCSAMPLER_TIMEDEP, self._boolFunc, vrayAttribute=True)),
                ("vray_GlobalDMC", XmlRenderAttribute("noiseThreshold", c4d.VP_VRAYBRIDGE_QMCSAMPLER_ADAPTTHR, self._floatFunc, vrayAttribute=True)),
                ("vray_GlobalDMC", XmlRenderAttribute("globalSubdivsMult", c4d.VP_VRAYBRIDGE_QMCSAMPLER_SUBDIVMULT, self._floatFunc, vrayAttribute=True)),
                ("vray_GlobalDMC", XmlRenderAttribute("minSample", c4d.VP_VRAYBRIDGE_QMCSAMPLER_ADAPSAMP, self._floatFunc, vrayAttribute=True)),
                
                ("vray_Environment", XmlRenderAttribute("giEnvironment", c4d.VP_VRAYBRIDGE_ENVIRONMENT_BGNOGI, self._boolFunc, vrayAttribute=True)),
                ("vray_Environment", XmlRenderAttribute("giColor", c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIBACKGROUND, self._colorFunc, vrayAttribute=True)),
                ("vray_Environment", XmlRenderAttribute("giMulti", c4d.VP_VRAYBRIDGE_ENVIRONMENT_GICOLORMULT, self._floatFunc, vrayAttribute=True)),
                ("vray_Environment", XmlRenderAttribute("giRotH", c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIMAPROTH, self._floatFunc, modifierFunction=self._angleToRad, vrayAttribute=True)),
                ("vray_Environment", XmlRenderAttribute("giRotV", c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIMAPROTP, self._floatFunc, modifierFunction=self._angleToRad, vrayAttribute=True)),
                #("vray_Environment", XmlRenderAttribute("giMapShader", c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIBACKGROUNDTEX, self._utilityShaderFunc, vrayAttribute=True)),
                #("vray_Environment", XmlRenderAttribute("giMapShaderPath", c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIBACKGROUNDTEX, self._bitmapFunc, vrayAttribute=True)),
                ("vray_Environment", XmlRenderAttribute("giMapShaderType", c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIMAPTYPE, self._renderStrTypeFunc, vrayAttribute=True)),
                
                ("vray_Environment", XmlRenderAttribute("rrOn", c4d.VP_VRAYBRIDGE_ENVIRONMENT_BGNOREFL, self._boolFunc, vrayAttribute=True)),
                ("vray_Environment", XmlRenderAttribute("rrColor", c4d.VP_VRAYBRIDGE_ENVIRONMENT_REFLBACKGROUND, self._colorFunc, vrayAttribute=True)),
                ("vray_Environment", XmlRenderAttribute("rrMulti", c4d.VP_VRAYBRIDGE_ENVIRONMENT_REFLCOLORMULT, self._floatFunc, vrayAttribute=True)),
                ("vray_Environment", XmlRenderAttribute("rrRotH", c4d.VP_VRAYBRIDGE_ENVIRONMENT_REFLMAPROTH, self._floatFunc, modifierFunction=self._angleToRad, vrayAttribute=True)),
                ("vray_Environment", XmlRenderAttribute("rrRotV", c4d.VP_VRAYBRIDGE_ENVIRONMENT_REFLMAPROTP, self._floatFunc, modifierFunction=self._angleToRad, vrayAttribute=True)),
                #("vray_Environment", XmlRenderAttribute("rrMapShader", c4d.VP_VRAYBRIDGE_ENVIRONMENT_REFLBACKGROUNDTEX, self._utilityShaderFunc, vrayAttribute=True)),
                #("vray_Environment", XmlRenderAttribute("rrMapShaderPath", c4d.VP_VRAYBRIDGE_ENVIRONMENT_REFLBACKGROUNDTEX, self._strFunc, vrayAttribute=True)),
                ("vray_Environment", XmlRenderAttribute("rrMapShaderType", c4d.VP_VRAYBRIDGE_ENVIRONMENT_REFLMAPTYPE, self._renderStrTypeFunc, vrayAttribute=True)),
                
                ("vray_Environment", XmlRenderAttribute("refractEnvironment", c4d.VP_VRAYBRIDGE_ENVIRONMENT_BGNOREFR, self._boolFunc, vrayAttribute=True)),
                ("vray_Environment", XmlRenderAttribute("refractColor", c4d.VP_VRAYBRIDGE_ENVIRONMENT_REFRBACKGROUND, self._colorFunc, vrayAttribute=True)),
                ("vray_Environment", XmlRenderAttribute("refractMulti", c4d.VP_VRAYBRIDGE_ENVIRONMENT_REFRMAPMUL, self._floatFunc, vrayAttribute=True)),
                
                ("vray_ColorMapping", XmlRenderAttribute("type", c4d.VP_VRAYBRIDGE_COLORMAPPING_TYPE, self._renderStrTypeFunc, vrayAttribute=True)),
                ("vray_ColorMapping", XmlRenderAttribute("mode", c4d.VP_VRAYBRIDGE_COLORMAPPING_ADAPTATION, self._vrayMappingAdaptionFunc, vrayAttribute=True)),
                ("vray_ColorMapping", XmlRenderAttribute("multiplier", c4d.VP_VRAYBRIDGE_COLORMAPPING_MULTIPLIER, self._floatFunc, vrayAttribute=True)),
                ("vray_ColorMapping", XmlRenderAttribute("burnValue", c4d.VP_VRAYBRIDGE_COLORMAPPING_BURN, self._floatFunc, vrayAttribute=True)),
                ("vray_ColorMapping", XmlRenderAttribute("multiplier", c4d.VP_VRAYBRIDGE_COLORMAPPING_DARKMUL, self._floatFunc, vrayAttribute=True)),
                ("vray_ColorMapping", XmlRenderAttribute("burnValue", c4d.VP_VRAYBRIDGE_COLORMAPPING_BRIGHTMUL, self._floatFunc, vrayAttribute=True)),
                ("vray_ColorMapping", XmlRenderAttribute("gamma", c4d.VP_VRAYBRIDGE_COLORMAPPING_GAMMA, self._vrayMappingAdaptionFunc, vrayAttribute=True)),
                ("vray_ColorMapping", XmlRenderAttribute("subpixelMapping", c4d.VP_VRAYBRIDGE_COLORMAPPING_SUBPIXEL, self._boolFunc, vrayAttribute=True)),
                ("vray_ColorMapping", XmlRenderAttribute("clampOutput", c4d.VP_VRAYBRIDGE_COLORMAPPING_CLAMP, self._boolFunc, vrayAttribute=True)),
                ("vray_ColorMapping", XmlRenderAttribute("clampLevel", c4d.VP_VRAYBRIDGE_COLORMAPPING_CLAMPLEVEL, self._floatFunc, vrayAttribute=True)),
                ("vray_ColorMapping", XmlRenderAttribute("affectBG", c4d.VP_VRAYBRIDGE_COLORMAPPING_AFFECTBG, self._boolFunc, vrayAttribute=True)),
                ("vray_ColorMapping", XmlRenderAttribute("linearWorkflow", c4d.VP_VRAYBRIDGE_COLORMAPPING_LWF, self._boolFunc, vrayAttribute=True)),
                ("vray_GlobalIllumination", XmlRenderAttribute("enableGI", c4d.VP_VRAYBRIDGE_GI_ON, self._boolFunc, vrayAttribute=True)),
                ("vray_GlobalIllumination", XmlRenderAttribute("primaryEngine", c4d.VP_VRAYBRIDGE_GIENGINE1, self._renderStrTypeFunc, vrayAttribute=True)),
                ("vray_GlobalIllumination", XmlRenderAttribute("secondaryEngine", c4d.VP_VRAYBRIDGE_GIENGINE2, self._renderStrTypeFunc, vrayAttribute=True)),
                ("vray_GlobalIllumination", XmlRenderAttribute("refractCaustics", c4d.VP_VRAYBRIDGE_GI_REFRACTIVE, self._boolFunc, vrayAttribute=True)),
                ("vray_GlobalIllumination", XmlRenderAttribute("reflectCaustics", c4d.VP_VRAYBRIDGE_GI_REFLECTIVE, self._boolFunc, vrayAttribute=True)),
                ("vray_IrradianceMap", XmlRenderAttribute("minRate", c4d.VP_VRAYBRIDGE_IRRADMINRATE, self._floatFunc, vrayAttribute=True)),
                ("vray_IrradianceMap", XmlRenderAttribute("maxRate", c4d.VP_VRAYBRIDGE_IRRADMAXRATE, self._floatFunc, vrayAttribute=True)),
                ("vray_IrradianceMap", XmlRenderAttribute("subdivs", c4d.VP_VRAYBRIDGE_IRRADSUBDIV, self._floatFunc, vrayAttribute=True)),
                ("vray_IrradianceMap", XmlRenderAttribute("interpSamples", c4d.VP_VRAYBRIDGE_IRRADINTSAMPLES, self._floatFunc, vrayAttribute=True)),
                ("vray_IrradianceMap", XmlRenderAttribute("interpFrames", c4d.VP_VRAYBRIDGE_IRRADINTFRAMES, self._floatFunc, vrayAttribute=True)),
                ("vray_IrradianceMap", XmlRenderAttribute("showCalcPhase", c4d.VP_VRAYBRIDGE_IRRADSHOWCALC, self._boolFunc, vrayAttribute=True)),
                ("vray_IrradianceMap", XmlRenderAttribute("Mode", c4d.VP_VRAYBRIDGE_IRRADMAPMODE, self._renderStrTypeFunc, vrayAttribute=True)),
                ("vray_Caustics", XmlRenderAttribute("enableCaustics", c4d.VP_VRAYBRIDGE_CAUSTICSON, self._boolFunc, vrayAttribute=True)),
                ("vray_Caustics", XmlRenderAttribute("searchDist", c4d.VP_VRAYBRIDGE_CAUSTICSSEARCHDIST, self._floatFunc, vrayAttribute=True)),
                ("vray_Caustics", XmlRenderAttribute("maxPhotons", c4d.VP_VRAYBRIDGE_CAUSTICSMAXPHOTONS, self._floatFunc, vrayAttribute=True)),
                ("vray_Caustics", XmlRenderAttribute("maxDensity", c4d.VP_VRAYBRIDGE_CAUSTICSMAXDENSITY, self._floatFunc, vrayAttribute=True)),
                ("vray_Caustics", XmlRenderAttribute("multiplier", c4d.VP_VRAYBRIDGE_CAUSTICSMULT, self._floatFunc, vrayAttribute=True)),
                ("vray_Caustics", XmlRenderAttribute("directVis", c4d.VP_VRAYBRIDGE_CAUSTICSSHOWCALC, self._boolFunc, vrayAttribute=True))
                            ]
    
    def _initMaterialArray(self):
        """Store each recognized material attribute in xml.
        """
        if self._vrayMaterials:
            if (self.VRAY3):
                self.VRAY_USE_REFRACTION    = c4d.VRAYMATERIAL_USE_REFRACTION
                self.VRAY_REFR_SHADER       = c4d.VRAYMATERIAL_REFRACT_SHADER
                self.VRAY_REFR_TEXTUREMULT  = c4d.VRAYMATERIAL_REFRACT_TEXTUREMULT
                self.VRAY_REFR_COLOR        = c4d.VRAYMATERIAL_REFRACT_COLOR
                self.VRAY_REFR_COLORMULT    = c4d.VRAYMATERIAL_REFRACT_COLOR_MULT
                self.VRAY_REFR_DOSHADOW     = c4d.VRAYMATERIAL_REFRACT_DOSHADOW
                self.VRAY_REFR_GLOSS        = c4d.VRAYMATERIAL_REFRACT_GLOSSINESS
                self.VRAY_REFR_GLOSSSHADER  = c4d.VRAYMATERIAL_REFRACT_GLOSSINESSSHADER
                self.VRAY_REFR_GLOSSTEXTUREMULT  = c4d.VRAYMATERIAL_REFRACT_GLOSSINESSTEXMULT
                self.VRAY_REFR_GLOSSIOR     = c4d.VRAYMATERIAL_REFRACT_IOR
                self.VRAY_USE_WEIGHT        = c4d.VRAYMATERIAL_USE_MAT_WEIGHT
                self.VRAY_WEIGHT_SHADER     = c4d.VRAYMATERIAL_WEIGHT_SHADER
                self.VRAY_WEIGHT_TEXINVERT  = c4d.VRAYMATERIAL_WEIGHT_TEXINVERT
            else:
                self.VRAY_USE_REFRACTION    = c4d.VRAYMATERIAL_USE_TRANSPARENCY
                self.VRAY_REFR_SHADER       = c4d.VRAYMATERIAL_TRANSPARENCY_SHADER
                self.VRAY_REFR_TEXTUREMULT  = c4d.VRAYMATERIAL_TRANSPARENCY_TEXTUREMULT
                self.VRAY_REFR_COLOR        = c4d.VRAYMATERIAL_TRANSPARENCY_COLOR
                self.VRAY_REFR_COLORMULT    = c4d.VRAYMATERIAL_TRANSPARENCY_COLOR_MULT
                self.VRAY_REFR_DOSHADOW     = c4d.VRAYMATERIAL_TRANSPARENCY_DOSHADOW
                self.VRAY_REFR_GLOSS        = c4d.VRAYMATERIAL_TRANSPARENCY_GLOSSINESS
                self.VRAY_REFR_GLOSSSHADER  = c4d.VRAYMATERIAL_TRANSPARENCY_GLOSSINESSSHADER
                self.VRAY_REFR_GLOSSTEXTUREMULT  = c4d.VRAYMATERIAL_TRANSPARENCY_GLOSSINESSTEXMULT
                self.VRAY_REFR_GLOSSIOR     = c4d.VRAYMATERIAL_TRANSPARENCY_IOR
                self.VRAY_USE_WEIGHT        = c4d.VRAYMATERIAL_USE_TRANSP
                self.VRAY_WEIGHT_SHADER     = c4d.VRAYMATERIAL_TRANSP_SHADER
                self.VRAY_WEIGHT_TEXINVERT  = c4d.VRAYMATERIAL_TRANSP_TEXINVERT
            
        
        # Channels list for disabling
        self._stdChannels = [
            c4d.MATERIAL_USE_COLOR,
            c4d.MATERIAL_USE_DIFFUSION,
            c4d.MATERIAL_USE_LUMINANCE
                            ]
        
        if self._vrayMaterials:
            
            self._vrayChannels =    [
                c4d.VRAYMATERIAL_USE_MATTE,
                self.VRAY_USE_REFRACTION,
                c4d.VRAYMATERIAL_USE_LUMINANCE, 
                c4d.MATERIAL_USE_BUMP
                                    ]
        
            self._vrayMaterialStr = {
                #----- vray_str : (vray_desc, std_str)
                ("specular_mode", "phong") : (c4d.VRAYMATERIAL_SPECULAR1_MODE_PHONG, ("specular_mode", "plastic")),
                ("specular_mode", "blinn") : (c4d.VRAYMATERIAL_SPECULAR1_MODE_BLINN,("specular_mode", "metal")),
                ("flake_filtering", "Directional") : (c4d.VRAYMATERIAL_SPECULAR1_MODE_PHONG, ("specular_mode", "plastic")),
                ("flake_filtering", "Simple") : (c4d.VRAYMATERIAL_SPECULAR1_MODE_PHONG, ("specular_mode", "plastic")),
                ("flake_mapping_type", "flake_mapping_type") : (c4d.VRAYMATERIAL_SPECULAR1_MODE_BLINN,("specular_mode", "metal")),
                ("sss2_single_scatter", "None") : (0,("0", "0")),
                ("sss2_single_scatter", "Single") : (1,("1", "1")),
                ("sss2_single_scatter", "Raytraced (solid)") : (2,("2", "2")),
                ("sss2_single_scatter", "Raytraced (refractive)") : (3,("3", "3")),
                ("displacementmod_type", "0") : (1,(1,1)),
                ("displacementmod_type", "1") : (0,(0,0)),
                                    }
            
            self._materialAttributes =  [
                XmlMaterialAttribute("environmentMap", c4d.MATERIAL_COLOR_SHADER, c4d.MATERIAL_USE_COLOR, self._bitmapFunc),
                #----- Standard->Vray properties
                XmlMaterialAttribute("opacity_amount", self.VRAY_REFR_TEXTUREMULT, self.VRAY_USE_REFRACTION, self._stdOpacityFunc),
                XmlMaterialAttribute("vrrefraf_reflmap", c4d.VRAYMATERIAL_SPECULAR1_SHADER, c4d.VRAYMATERIAL_USE_SPECULAR1, self._bitmapFunc),
                XmlMaterialAttribute("self_illum_slider", c4d.VRAYMATERIAL_LUMINANCE_COLOR_MULT, c4d.VRAYMATERIAL_USE_LUMINANCE, self._floatFunc),
                XmlMaterialAttribute("diffuse_color", c4d.VRAYMATERIAL_COLOR1_COLOR, c4d.VRAYMATERIAL_USE_COLOR1, self._colorFunc),
                XmlMaterialAttribute("specular_color", c4d.VRAYMATERIAL_SPECULAR1_COLOR, c4d.VRAYMATERIAL_USE_SPECULAR1, self._colorFunc),
                XmlMaterialAttribute("specular_width", c4d.VRAYMATERIAL_SPECULAR1_HIGHLIGHTGLOSS, c4d.VRAYMATERIAL_USE_SPECULAR1, self._percentFunc, self._specWidthFunc),
                XmlMaterialAttribute("diffuse_map", c4d.VRAYMATERIAL_COLOR1_SHADER, c4d.VRAYMATERIAL_USE_COLOR1, self._bitmapFunc),
                XmlMaterialAttribute("diffusemap", c4d.VRAYMATERIAL_COLOR1_SHADER, c4d.VRAYMATERIAL_USE_COLOR1, self._bitmapFunc),
                XmlMaterialAttribute("bump_map", c4d.VRAYMATERIAL_BUMP_SHADER, c4d.VRAYMATERIAL_USE_BUMP, self._bitmapFunc),
                XmlMaterialAttribute("reflection_map", c4d.VRAYMATERIAL_SPECULAR1_SHADER, c4d.VRAYMATERIAL_USE_SPECULAR1, self._bitmapFunc),
                XmlMaterialAttribute("refraction_map", self.VRAY_WEIGHT_SHADER, self.VRAY_USE_WEIGHT, self._bitmapFunc),
                XmlMaterialAttribute("opacity_map", self.VRAY_WEIGHT_SHADER, self.VRAY_USE_REFRACTION, self._bitmapFunc),
                #Find some way to convert Max std Blend mat to C4D VrayBlend mat..
                #Std Blend COAT BLENDAMOUNT [First Coat Only]
                XmlMaterialAttribute("mask", self.VRAY_WEIGHT_SHADER, self.VRAY_USE_REFRACTION, None),
                #Std Blend mat to C4D VrayBlend mat.. [Base and First Coat Only]
                XmlMaterialAttribute("material1", c4d.VRAYBLENDMATERIAL_PARAMS_LINK10, c4d.VRAYBLENDMATERIAL_PARAMS_USELINK10, self._vrBlendSubmatFunc),
                XmlMaterialAttribute("material2", c4d.VRAYBLENDMATERIAL_PARAMS_LINK9, c4d.VRAYBLENDMATERIAL_PARAMS_USELINK9, self._vrBlendSubmatFunc),
                
                #----- Vray->Vray properties
                
                XmlMaterialAttribute("vraybump_map", c4d.VRAYMATERIAL_BUMP_SHADER, c4d.VRAYMATERIAL_USE_BUMP, self._bitmapFunc),
                XmlMaterialAttribute("vraybump_value", c4d.VRAYMATERIAL_BUMP_BUMPTEXMULT, c4d.VRAYMATERIAL_USE_BUMP, self._floatFunc, modifierFunction=self._multiplyBy,modifierParam=1.5),
                XmlMaterialAttribute("vrayopacity_map", self.VRAY_WEIGHT_SHADER, self.VRAY_USE_REFRACTION, self._bitmapFunc),
                XmlMaterialAttribute("vrayselfillum_map", c4d.VRAYMATERIAL_LUMINANCE_SHADER, c4d.VRAYMATERIAL_USE_LUMINANCE, self._bitmapFunc),
                XmlMaterialAttribute("self_illumination_map", c4d.VRAYMATERIAL_LUMINANCE_SHADER, c4d.VRAYMATERIAL_USE_LUMINANCE, self._bitmapFunc),
                XmlMaterialAttribute("vrayself_illumination_value", c4d.VRAYMATERIAL_LUMINANCE_SHADER_MULTIPLIER, c4d.VRAYMATERIAL_USE_LUMINANCE, self._floatFunc, modifierFunction=self._divideBy,modifierParam=100),
                XmlMaterialAttribute("vrayselfillum_color", c4d.VRAYMATERIAL_LUMINANCE_COLOR, c4d.VRAYMATERIAL_USE_LUMINANCE, self._colorFunc),
                XmlMaterialAttribute("vrayselfillum_multiplier", c4d.VRAYMATERIAL_LUMINANCE_COLOR_MULT, c4d.VRAYMATERIAL_USE_LUMINANCE, self._floatFunc),
                
                XmlMaterialAttribute("color", c4d.VRAYMATERIAL_LUMINANCE_COLOR, c4d.VRAYMATERIAL_USE_LUMINANCE, self._colorFunc),
                XmlMaterialAttribute("vraylightlightmap", c4d.VRAYMATERIAL_LUMINANCE_SHADER, c4d.VRAYMATERIAL_USE_LUMINANCE, self._bitmapFunc),
                XmlMaterialAttribute("vraylightopacitymap", self.VRAY_WEIGHT_SHADER, self.VRAY_USE_REFRACTION, self._bitmapFunc),
                XmlMaterialAttribute("multiplier", c4d.VRAYMATERIAL_LUMINANCE_COLOR_MULT, c4d.VRAYMATERIAL_USE_LUMINANCE, self._floatFunc, modifierFunction=self._multiplyBy,modifierParam=1),
                XmlMaterialAttribute("multiplier", c4d.VRAYMATERIAL_LUMINANCE_SHADER_MULTIPLIER, c4d.VRAYMATERIAL_USE_LUMINANCE, self._floatFunc, modifierFunction=self._multiplyBy,modifierParam=1),
                XmlMaterialAttribute("twoSided", c4d.VRAYMATERIAL_LUMINANCE_EMITBACK, c4d.VRAYMATERIAL_USE_LUMINANCE, self._boolFunc),
                XmlMaterialAttribute("compemsate_exposure", c4d.VRAYMATERIAL_LUMINANCE_COMPENSATE, c4d.VRAYMATERIAL_USE_LUMINANCE, self._boolFunc),
                XmlMaterialAttribute("directLight_on", c4d.VRAYMATERIAL_LUMINANCE_DIRECTILLUM, c4d.VRAYMATERIAL_USE_LUMINANCE, self._boolFunc),
                XmlMaterialAttribute("directLight_subdivs", c4d.VRAYMATERIAL_LUMINANCE_SUBDIVS, c4d.VRAYMATERIAL_USE_LUMINANCE, self._intFunc),

                XmlMaterialAttribute("vraydiffuse_color", c4d.VRAYMATERIAL_COLOR1_COLOR, c4d.VRAYMATERIAL_USE_COLOR1, self._colorFunc),
                XmlMaterialAttribute("vraydiffuse_map", c4d.VRAYMATERIAL_COLOR1_SHADER, c4d.VRAYMATERIAL_USE_COLOR1, self._bitmapFunc),
                XmlMaterialAttribute("vraydiffuse_value", c4d.VRAYMATERIAL_COLOR1_TEXTUREMULT, c4d.VRAYMATERIAL_USE_COLOR1, self._floatFunc, modifierFunction=self._divideBy,modifierParam=100),
                XmlMaterialAttribute("vrayreflection_color", c4d.VRAYMATERIAL_SPECULAR1_COLOR, c4d.VRAYMATERIAL_USE_SPECULAR1, self._colorFunc),
                XmlMaterialAttribute("vrayreflection_map", c4d.VRAYMATERIAL_SPECULAR1_SHADER, c4d.VRAYMATERIAL_USE_SPECULAR1, self._bitmapFunc),
                XmlMaterialAttribute("vrayreflection_value", c4d.VRAYMATERIAL_SPECULAR1_TEXTUREMULT, c4d.VRAYMATERIAL_USE_SPECULAR1, self._floatFunc, modifierFunction=self._divideBy,modifierParam=100),
                XmlMaterialAttribute("vrayreflection_glossiness", c4d.VRAYMATERIAL_SPECULAR1_REFLECTIONGLOSS, c4d.VRAYMATERIAL_USE_SPECULAR1, self._floatFunc),
                XmlMaterialAttribute("vrayreflection_glossiness_map", c4d.VRAYMATERIAL_SPECULAR1_REFLECTIONGLOSSSHADER, c4d.VRAYMATERIAL_USE_SPECULAR1, self._bitmapFunc),
                XmlMaterialAttribute("vrayreflectionGlossiness_value", c4d.VRAYMATERIAL_SPECULAR1_REFLECTIONGLOSSTEXMULT, c4d.VRAYMATERIAL_USE_SPECULAR1, self._floatFunc, modifierFunction=self._divideBy,modifierParam=100),
                XmlMaterialAttribute("vrayreflection_fresnel", c4d.VRAYMATERIAL_SPECULAR1_USEFRESNEL, c4d.VRAYMATERIAL_USE_SPECULAR1, self._boolFunc),
                XmlMaterialAttribute("vrayreflection_lockGloss", c4d.VRAYMATERIAL_SPECULAR1_LINKGLOSSINESS, c4d.VRAYMATERIAL_USE_SPECULAR1, self._boolFunc),
                XmlMaterialAttribute("vrayreflection_ior", c4d.VRAYMATERIAL_SPECULAR1_FRESNELIOR1, c4d.VRAYMATERIAL_USE_SPECULAR1, self._floatFunc),
                XmlMaterialAttribute("vrayhilight_glossiness", c4d.VRAYMATERIAL_SPECULAR1_HIGHLIGHTGLOSS, c4d.VRAYMATERIAL_USE_SPECULAR1, self._floatFunc),
                XmlMaterialAttribute("vrayhilight_glossiness_map", c4d.VRAYMATERIAL_SPECULAR1_HIGHLIGHTGLOSSSHADER, c4d.VRAYMATERIAL_USE_SPECULAR1, self._bitmapFunc),
                XmlMaterialAttribute("vrayhilightGlossiness_value", c4d.VRAYMATERIAL_SPECULAR1_HIGHLIGHTGLOSSTEXMULT, c4d.VRAYMATERIAL_USE_SPECULAR1, self._floatFunc, modifierFunction=self._divideBy,modifierParam=100),
                XmlMaterialAttribute("vrayrefraction_color", self.VRAY_REFR_COLOR, self.VRAY_USE_WEIGHT, self._colorFunc),
                XmlMaterialAttribute("vrayrefraction_map", self.VRAY_WEIGHT_SHADER, self.VRAY_USE_WEIGHT, self._bitmapFunc),
                XmlMaterialAttribute("vrayrefraction_value", self.VRAY_REFR_TEXTUREMULT, self.VRAY_USE_WEIGHT, self._floatFunc),
                XmlMaterialAttribute("vrayrefraction_affectShadows", self.VRAY_REFR_DOSHADOW, self.VRAY_USE_WEIGHT, self._boolFunc),
                XmlMaterialAttribute("vrayrefraction_glossiness", self.VRAY_REFR_GLOSS, self.VRAY_USE_WEIGHT, self._floatFunc),
                XmlMaterialAttribute("vrayrefraction_glossiness_map", self.VRAY_REFR_GLOSSSHADER, self.VRAY_USE_WEIGHT, self._bitmapFunc),
                XmlMaterialAttribute("vrayrefractionGlossiness_value", self.VRAY_REFR_GLOSSTEXTUREMULT, self.VRAY_USE_WEIGHT, self._floatFunc, modifierFunction=self._divideBy,modifierParam=100),
                XmlMaterialAttribute("vrayrefraction_ior", self.VRAY_REFR_GLOSSIOR, self.VRAY_USE_WEIGHT, self._floatFunc),
                XmlMaterialAttribute("vrayreflection_lockIOR", None, None, self._fresnelLockFunc),
                XmlMaterialAttribute("vraybrdf_type", c4d.VRAYMATERIAL_SPECULAR1_MODE, c4d.VRAYMATERIAL_USE_SPECULAR1, self._intFunc),
                
                #VRay Engine Environment overrides
                
                XmlMaterialAttribute("giMapShader", c4d.VP_VRAYBRIDGE_ENVIRONMENT_BACKGROUNDTEX, None, None),
                XmlMaterialAttribute("giMapShader", c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIBACKGROUNDTEX, None, None),
                XmlMaterialAttribute("rrMapShader", c4d.VP_VRAYBRIDGE_ENVIRONMENT_REFLBACKGROUNDTEX, None, None),
                
                #VRayDisplacementModifier parameters
                XmlMaterialAttribute("displacementmod_type", c4d.VRAYDISPLACEMATERIAL_TYPE, None, self._displacementTypeFunc),
                XmlMaterialAttribute("displacementmod_texmap", c4d.VRAYDISPLACEMATERIAL_TEXTURE, None, self._bitmapFunc),
                XmlMaterialAttribute("displacementmod_amount", c4d.VRAYDISPLACEMATERIAL_AMOUNT, None, self._floatFunc),
                XmlMaterialAttribute("displacementmod_shift", c4d.VRAYDISPLACEMATERIAL_SHIFT, None, self._floatFunc),
                XmlMaterialAttribute("displacementmod_waterLevelOn", c4d.VRAYDISPLACEMATERIAL_USEWATERLEVEL, None, self._boolFunc),
                XmlMaterialAttribute("displacementmod_waterLevelValue", c4d.VRAYDISPLACEMATERIAL_WATERLEVEL, None, self._floatFunc),
                XmlMaterialAttribute("displacementmod_resolution", c4d.VRAYDISPLACEMATERIAL_RESOLUTION, None, self._intFunc),
                XmlMaterialAttribute("displacementmod_precision", c4d.VRAYDISPLACEMATERIAL_PRECISION, None, self._intFunc),
                XmlMaterialAttribute("displacementmod_tightBounds", c4d.VRAYDISPLACEMATERIAL_TBOUNDS2D, None, self._boolFunc),
                #XmlMaterialAttribute("displacementmod_relativeToBBox", c4d.VRAYDISPLACEMATERIAL_TBOUNDS2D, None, self._boolFunc),
                
                #VRayBlend COAT BLENDAMOUNT multipliers [First Four Coats Only]
                XmlMaterialAttribute("texturemap_blend_mult0", self.VRAY_REFR_TEXTUREMULT, self.VRAY_USE_REFRACTION, None),
                XmlMaterialAttribute("texturemap_blend_mult1", self.VRAY_REFR_TEXTUREMULT, self.VRAY_USE_REFRACTION, None),
                XmlMaterialAttribute("texturemap_blend_mult2", self.VRAY_REFR_TEXTUREMULT, self.VRAY_USE_REFRACTION, None),
                XmlMaterialAttribute("texturemap_blend_mult3", self.VRAY_REFR_TEXTUREMULT, self.VRAY_USE_REFRACTION, None),
                #VRayBlend COAT BLENDAMOUNT maps [First Four Coats Only]
                XmlMaterialAttribute("coatShader0", c4d.SLA_FUSION_BLEND_CHANNEL, self.VRAY_USE_REFRACTION, None),
                XmlMaterialAttribute("coatShader1", c4d.SLA_FUSION_BLEND_CHANNEL, self.VRAY_USE_REFRACTION, None),
                XmlMaterialAttribute("coatShader2", c4d.SLA_FUSION_BLEND_CHANNEL, self.VRAY_USE_REFRACTION, None),
                XmlMaterialAttribute("coatShader3", c4d.SLA_FUSION_BLEND_CHANNEL, self.VRAY_USE_REFRACTION, None),
                #VrayBlend mat to C4D VrayBlend mat.. [First Four Coats Only]
                XmlMaterialAttribute("base_material", c4d.VRAYBLENDMATERIAL_PARAMS_LINK10, c4d.VRAYBLENDMATERIAL_PARAMS_USELINK10, self._vrBlendSubmatFunc),
                XmlMaterialAttribute("coatMaterial0", c4d.VRAYBLENDMATERIAL_PARAMS_LINK9, c4d.VRAYBLENDMATERIAL_PARAMS_USELINK9, self._vrBlendSubmatFunc),
                XmlMaterialAttribute("coatMaterial1", c4d.VRAYBLENDMATERIAL_PARAMS_LINK8, c4d.VRAYBLENDMATERIAL_PARAMS_USELINK8, self._vrBlendSubmatFunc),
                XmlMaterialAttribute("coatMaterial2", c4d.VRAYBLENDMATERIAL_PARAMS_LINK7, c4d.VRAYBLENDMATERIAL_PARAMS_USELINK7, self._vrBlendSubmatFunc),
                XmlMaterialAttribute("coatMaterial3", c4d.VRAYBLENDMATERIAL_PARAMS_LINK6, c4d.VRAYBLENDMATERIAL_PARAMS_USELINK6, self._vrBlendSubmatFunc),
                #VRayMaterialWrapper (Non-Matte)
                XmlMaterialAttribute("wrapper_base_mat", c4d.VRAYMATERIAL_COLOR1_SHADER, c4d.VRAYMATERIAL_USE_COLOR1, self._vrWrapperSubmatFunc),
                
                #VRayTwoSided Material
                XmlMaterialAttribute("translucency", c4d.VRAY2SIDEDMATERIAL_PARAMS_TRANSLCOLOR, None, self._colorFunc),
                #XmlMaterialAttribute("backMtlOn", c4d.VRAY2SIDEDMATERIAL_PARAMS_LINK1, None, self._twoSidedBackMatFunc),
                XmlMaterialAttribute("texmapTranslucencyMultiplier", c4d.VRAY2SIDEDMATERIAL_PARAMS_TRANSLCOLOR_MULT, None, self._floatFunc),
                #XmlMaterialAttribute("texmapTranslucencyOn", self.VRAY_REFR_TEXTUREMULT, None, self._boolFunc),
                #XmlMaterialAttribute("force1SidedSubMtls", self.VRAY_REFR_TEXTUREMULT, None, self._boolFunc),
                XmlMaterialAttribute("frontMaterial", c4d.VRAY2SIDEDMATERIAL_PARAMS_LINK1, None, self._matFunc),
                XmlMaterialAttribute("backMaterial", c4d.VRAY2SIDEDMATERIAL_PARAMS_LINK2, None, self._matFunc),
                
                #VRayOverride Material
                XmlMaterialAttribute("baseMaterial", c4d.VRAYOVERRIDEMATERIAL_PARAMS_LINK1, None, self._matFunc),
                XmlMaterialAttribute("giMaterial", c4d.VRAYOVERRIDEMATERIAL_PARAMS_LINK2, None, self._matFunc),
                XmlMaterialAttribute("reflectMaterial", c4d.VRAYOVERRIDEMATERIAL_PARAMS_LINK3, None, self._matFunc),
                XmlMaterialAttribute("refractMaterial", c4d.VRAYOVERRIDEMATERIAL_PARAMS_LINK4, None, self._matFunc),
                XmlMaterialAttribute("shadowMaterial", c4d.VRAYOVERRIDEMATERIAL_PARAMS_LINK5, None, self._matFunc),
                
                #VRayFastSSS2 Material
                XmlMaterialAttribute("sss2_texmap_overall_color", c4d.VRAYFASTSSS2MATERIAL_SSS_OVERALLCOLORSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("sss2_texmap_diffuse_color", c4d.VRAYFASTSSS2MATERIAL_SSS_DIFFUSECOLORSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("sss2_texmap_diffuse_amount", c4d.VRAYFASTSSS2MATERIAL_SSS_DIFFUSEAMOUNTSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("sss2_texmap_specular_color", c4d.VRAYFASTSSS2MATERIAL_SSS_SPECULARCOLORSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("sss2_texmap_specular_amount", c4d.VRAYFASTSSS2MATERIAL_SSS_SPECULARAMOUNTSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("sss2_texmap_specular_glossiness", c4d.VRAYFASTSSS2MATERIAL_SSS_SPECULARGLOSSINESSSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("sss2_texmap_sss_color", c4d.VRAYFASTSSS2MATERIAL_SSS_SSSCOLORSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("sss2_texmap_scatter_color", c4d.VRAYFASTSSS2MATERIAL_SSS_SCATTERSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("sss2_texmap_scatter_radius", c4d.VRAYFASTSSS2MATERIAL_SSS_SCATTERMULTSHADER, None, self._bitmapFunc),
                #XmlMaterialAttribute("sss2_texmap_bump", c4d.VRAYOVERRIDEMATERIAL_PARAMS_LINK1, None, self._bitmapFunc),
                #XmlMaterialAttribute("sss2_texmap_displacement", c4d.VRAYFASTSSS2MATERIAL_SSS_SSSCOLORSHADER, None, self._bitmapFunc),
                
                #XmlMaterialAttribute("sss2_preset", self.VRAY_REFR_GLOSS, None, self._floatFunc),
                XmlMaterialAttribute("sss2_scale", c4d.VRAYFASTSSS2MATERIAL_SSS_SCALE, None, self._floatFunc),
                XmlMaterialAttribute("sss2_IOR", c4d.VRAYFASTSSS2MATERIAL_SSS_IOR, None, self._floatFunc),
                #XmlMaterialAttribute("sss2_multiple_scattering", self.VRAY_REFR_GLOSS, None, self._materialStrTypeFunc),
                XmlMaterialAttribute("sss2_prepass_rate", c4d.VRAYFASTSSS2MATERIAL_SSS_PREPASS, None, self._intFunc),
                XmlMaterialAttribute("sss2_prepass_id", c4d.VRAYFASTSSS2MATERIAL_SSS_PREPASSID, None, self._intFunc),
                XmlMaterialAttribute("sss2_auto_calculate_density", c4d.VRAYFASTSSS2MATERIAL_SSS_AUTODENSITY, None, self._boolFunc),
                XmlMaterialAttribute("sss2_samples_per_unit_area", c4d.VRAYFASTSSS2MATERIAL_SSS_SAMPLESPERUNITAREA, None, self._floatFunc),
                XmlMaterialAttribute("sss2_surface_offset", c4d.VRAYFASTSSS2MATERIAL_SSS_SURFACEOFFSET, None, self._floatFunc),
                XmlMaterialAttribute("sss2_preview_samples", c4d.VRAYFASTSSS2MATERIAL_SSS_PREVIEWSAMPLES, None, self._boolFunc),
                XmlMaterialAttribute("sss2_max_distance", c4d.VRAYFASTSSS2MATERIAL_SSS_MAXDISTANCE, None, self._floatFunc),
                XmlMaterialAttribute("sss2_background_color", c4d.VRAYFASTSSS2MATERIAL_SSS_BGCOLOR, None, self._colorFunc),
                XmlMaterialAttribute("sss2_samples_color", c4d.VRAYFASTSSS2MATERIAL_SSS_SAMPLESCOLOR, None, self._colorFunc),
                XmlMaterialAttribute("sss2_diffuse_color", c4d.VRAYFASTSSS2MATERIAL_SSS_DIFFUSECOLOR, None, self._colorFunc),
                XmlMaterialAttribute("sss2_diffuse_amount", c4d.VRAYFASTSSS2MATERIAL_SSS_DIFFUSEAMOUNT, None, self._floatFunc),
                XmlMaterialAttribute("sss2_sub_surface_color", c4d.VRAYFASTSSS2MATERIAL_SSS_SSSCOLOR, None, self._colorFunc),
                XmlMaterialAttribute("sss2_scatter_color", c4d.VRAYFASTSSS2MATERIAL_SSS_SCATTERCOLOR, None, self._colorFunc),
                XmlMaterialAttribute("sss2_scatter_radius", c4d.VRAYFASTSSS2MATERIAL_SSS_SCATTERMULT, None, self._floatFunc),
                XmlMaterialAttribute("sss2_phase_function", c4d.VRAYFASTSSS2MATERIAL_SSS_PHASE, None, self._floatFunc),
                XmlMaterialAttribute("sss2_specular_color", c4d.VRAYFASTSSS2MATERIAL_SSS_SPECULARCOLOR, None, self._colorFunc),
                XmlMaterialAttribute("sss2_specular_amount", c4d.VRAYFASTSSS2MATERIAL_SSS_SPECULARAMOUNT, None, self._floatFunc),
                XmlMaterialAttribute("sss2_specular_glossiness", c4d.VRAYFASTSSS2MATERIAL_SSS_SPECULARGLOSSINESS, None, self._floatFunc),
                XmlMaterialAttribute("sss2_specular_subdivs", c4d.VRAYFASTSSS2MATERIAL_SSS_SPECULARSUBDIVS, None, self._intFunc),
                XmlMaterialAttribute("sss2_trace_reflections", c4d.VRAYFASTSSS2MATERIAL_SSS_SPECULARTRACE, None, self._boolFunc),
                XmlMaterialAttribute("sss2_reflection_depth", c4d.VRAYFASTSSS2MATERIAL_SSS_SPECULARDEPTH, None, self._intFunc),
                XmlMaterialAttribute("sss2_single_scatter", c4d.VRAYFASTSSS2MATERIAL_SSS_SINGLESCATTER, None, self._materialStrTypeFunc),
                XmlMaterialAttribute("sss2_single_scatter_subdivs", c4d.VRAYFASTSSS2MATERIAL_SSS_SUBDIVS, None, self._intFunc),
                XmlMaterialAttribute("sss2_refraction_depth", c4d.VRAYFASTSSS2MATERIAL_SSS_REFRACTIONDEPTH, None, self._intFunc),
                XmlMaterialAttribute("sss2_front_lighting", c4d.VRAYFASTSSS2MATERIAL_SSS_FRONTSCATTER, None, self._boolFunc),
                XmlMaterialAttribute("sss2_back_lighting", c4d.VRAYFASTSSS2MATERIAL_SSS_BACKSCATTER, None, self._boolFunc),
                XmlMaterialAttribute("sss2_scatter_gi", c4d.VRAYFASTSSS2MATERIAL_SSS_SCATTERGI, None, self._boolFunc),
                XmlMaterialAttribute("sss2_prepass_LOD_threshold", c4d.VRAYFASTSSS2MATERIAL_SSS_PREPASSLOD, None, self._floatFunc),
                #XmlMaterialAttribute("sss2_interpolation_accuracy", self.VRAY_REFR_GLOSS, None, self._floatFunc),
                #XmlMaterialAttribute("sss2_legacy_mode", self.VRAY_REFR_GLOSS, None, self._boolFunc),
                XmlMaterialAttribute("sss2_prepass_blur", c4d.VRAYFASTSSS2MATERIAL_SSS_PREPASSBLUR, None, self._floatFunc),
                #XmlMaterialAttribute("sss2_cutoff_threshold", self.VRAY_REFR_GLOSS, None, self._floatFunc),
                XmlMaterialAttribute("sss2_prepass_mode", c4d.VRAYFASTSSS2MATERIAL_SSS_PREPASSMODE, None, self._materialStrTypeFunc),
                XmlMaterialAttribute("sss2_prepass_fileName", c4d.VRAYFASTSSS2MATERIAL_SSS_PREPASSFILENAMESAVE, None, self._pathFunc),
                #XmlMaterialAttribute("sss2_texmap_bump_on", self.VRAY_REFR_GLOSS, None, self._boolFunc),
                #XmlMaterialAttribute("sss2_texmap_bump_multiplier", self.VRAY_REFR_GLOSS, None, self._floatFunc),
                #XmlMaterialAttribute("sss2_texmap_specular_color_on", self.VRAY_REFR_GLOSS, None, self._floatFunc),
                #XmlMaterialAttribute("sss2_texmap_specular_color_multiplier", self.VRAY_REFR_GLOSS, None, self._floatFunc),
                #XmlMaterialAttribute("sss2_texmap_specular_glossiness_on", self.VRAY_REFR_GLOSS, None, self._boolFunc),
                #XmlMaterialAttribute("sss2_texmap_specular_glossiness_multiplier", self.VRAY_REFR_GLOSS, None, self._floatFunc),
                #XmlMaterialAttribute("sss2_texmap_sss_color_on", self.VRAY_REFR_GLOSS, None, self._boolFunc),
                #XmlMaterialAttribute("sss2_texmap_sss_color_multiplier", self.VRAY_REFR_GLOSS, None, self._floatFunc),
                      
                #VRayCarPaint Material
                XmlMaterialAttribute("base_color", c4d.VRAYCARPAINTMATERIAL_BASECOLOR, None, self._colorFunc),
                XmlMaterialAttribute("texmap_base_color", c4d.VRAYCARPAINTMATERIAL_BASECOLORSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("texmap_base_reflection", c4d.VRAYCARPAINTMATERIAL_BASEREFLAMOUNTSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("texmap_base_glossiness", c4d.VRAYCARPAINTMATERIAL_BASEREFLGLOSSINESSSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("texmap_base_bump", c4d.VRAYCARPAINTMATERIAL_BASEBUMPSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("base_reflection", c4d.VRAYCARPAINTMATERIAL_BASEREFLAMOUNT, None, self._floatFunc),
                XmlMaterialAttribute("base_glossiness", c4d.VRAYCARPAINTMATERIAL_BASEREFLGLOSSINESS, None, self._floatFunc),
                XmlMaterialAttribute("base_trace_reflections", c4d.VRAYCARPAINTMATERIAL_BASETRACEREFLECTION, None, self._boolFunc),
                XmlMaterialAttribute("flake_color", c4d.VRAYCARPAINTMATERIAL_FLAKECOLOR, None, self._colorFunc),
                XmlMaterialAttribute("texmap_flake_color", c4d.VRAYCARPAINTMATERIAL_FLAKECOLORSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("texmap_flake_glossiness", c4d.VRAYCARPAINTMATERIAL_FLAKEGLOSSINESSSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("flake_glossiness", c4d.VRAYCARPAINTMATERIAL_FLAKEGLOSSINESS, None, self._floatFunc),
                XmlMaterialAttribute("flake_orientation", c4d.VRAYCARPAINTMATERIAL_FLAKEORIENTATION, None, self._floatFunc),
                XmlMaterialAttribute("texmap_flake_orientation", c4d.VRAYCARPAINTMATERIAL_FLAKEORIENTATIONSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("flake_density", c4d.VRAYCARPAINTMATERIAL_FLAKEDENSITY, None, self._floatFunc),
                XmlMaterialAttribute("flake_scale", c4d.VRAYCARPAINTMATERIAL_FLAKESCALE, None, self._floatFunc),
                XmlMaterialAttribute("flake_size", c4d.VRAYCARPAINTMATERIAL_FLAKESIZE, None, self._floatFunc),
                XmlMaterialAttribute("flake_seed", c4d.VRAYCARPAINTMATERIAL_FLAKESEED, None, self._floatFunc),
                XmlMaterialAttribute("flake_filtering", c4d.VRAYCARPAINTMATERIAL_FLAKEFILTERING, None, self._materialStrTypeFunc),
                XmlMaterialAttribute("flake_map_size", c4d.VRAYCARPAINTMATERIAL_FLAKEMAPSIZE, None, self._intFunc),
                XmlMaterialAttribute("flake_mapping_type", c4d.VRAYCARPAINTMATERIAL_FLAKEMAPTYPE, None, self._materialStrTypeFunc),
                XmlMaterialAttribute("flake_trace_reflections", c4d.VRAYCARPAINTMATERIAL_FLAKETRACEREFLECTION, None, self._boolFunc),
                XmlMaterialAttribute("coat_color", c4d.VRAYCARPAINTMATERIAL_COATCOLOR, None, self._colorFunc),
                XmlMaterialAttribute("texmap_coat_color", c4d.VRAYCARPAINTMATERIAL_COATCOLORSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("coat_strength", c4d.VRAYCARPAINTMATERIAL_COATSTRENGTH, None, self._floatFunc),
                XmlMaterialAttribute("texmap_coat_strength", c4d.VRAYCARPAINTMATERIAL_COATSTRENGTHSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("coat_glossiness", c4d.VRAYCARPAINTMATERIAL_COATGLOSSINESS, None, self._floatFunc),
                XmlMaterialAttribute("texmap_coat_glossiness", c4d.VRAYCARPAINTMATERIAL_COATGLOSSINESSSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("coat_trace_reflections", c4d.VRAYCARPAINTMATERIAL_COATTRACEREFLECTIONS, None, self._boolFunc),
                XmlMaterialAttribute("texmap_coat_bump", c4d.VRAYCARPAINTMATERIAL_COATBUMPSHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("trace_reflections", c4d.VRAYCARPAINTMATERIAL_TRACEREFLECTIONS, None, self._boolFunc),
                XmlMaterialAttribute("double_sided", c4d.VRAYCARPAINTMATERIAL_DOUBLESIDED, None, self._boolFunc),
                XmlMaterialAttribute("subdivs", c4d.VRAYCARPAINTMATERIAL_SUBDIVS, None, self._intFunc),
                XmlMaterialAttribute("cutoff_threshold", c4d.VRAYCARPAINTMATERIAL_CUTOFF, None, self._floatFunc),
                XmlMaterialAttribute("environment_priority", c4d.VRAYCARPAINTMATERIAL_ENVPRIORITY, None, self._intFunc),
                XmlMaterialAttribute("texmap_environment_override", c4d.VRAYCARPAINTMATERIAL_ENVOVERRIDESHADER, None, self._bitmapFunc),
                
                #Shellac mat to C4D VrayBlend mat.. [First Four Coats Only]
                XmlMaterialAttribute("shellacMtl1", c4d.VRAYBLENDMATERIAL_PARAMS_LINK10, c4d.VRAYBLENDMATERIAL_PARAMS_USELINK10, self._vrBlendSubmatFunc),
                XmlMaterialAttribute("shellacMtl2", c4d.VRAYBLENDMATERIAL_PARAMS_LINK9, c4d.VRAYBLENDMATERIAL_PARAMS_USELINK9, self._vrBlendSubmatFunc),
                                                                        ]
        
        elif self._usingOctane:
            
            self._octMaterialStr = {
                #----- octane_str : (octane_desc, std_str)
                                    }
            
            self._materialAttributes =  [
                
                #XmlMaterialAttribute("environmentMap", c4d.MATERIAL_COLOR_SHADER, c4d.MATERIAL_USE_COLOR, self._bitmapFunc),
                
                #----- Standard->Vray properties
                
                #
                
                #----- Vray->Vray properties
                
                #VrayLightMtl
                XmlMaterialAttribute("color", c4d.BBEMISSION_EFFIC_OR_TEX, c4d.OCTANE_MATERIAL_USE_EMISSION, self._colorToColorShaderFunc),
                XmlMaterialAttribute("multiplier", c4d.BLACKBODYEMISSION_POWER, c4d.OCTANE_MATERIAL_USE_EMISSION, self._floatFunc, modifierFunction=self._multiplyBy,modifierParam=1),
                
                #VrayStdMtl
                XmlMaterialAttribute("vraydiffuse_color", c4d.OCT_MATERIAL_DIFFUSE_COLOR, c4d.OCTANE_MATERIAL_USE_COLOR, self._colorFunc),
                XmlMaterialAttribute("vraydiffuse_map", c4d.OCT_MATERIAL_DIFFUSE_LINK, c4d.OCTANE_MATERIAL_USE_COLOR, self._bitmapFunc),
                XmlMaterialAttribute("diffuse_map", c4d.OCT_MATERIAL_DIFFUSE_LINK, c4d.OCTANE_MATERIAL_USE_COLOR, self._bitmapFunc),
                XmlMaterialAttribute("vraydiffuse_value", c4d.OCT_MATERIAL_DIFFUSE_MIX, c4d.OCTANE_MATERIAL_USE_COLOR, self._floatFunc, modifierFunction=self._divideBy,modifierParam=100),
                
                XmlMaterialAttribute("vrayreflection_color", c4d.OCT_MATERIAL_SPECULAR_COLOR, c4d.OCTANE_MATERIAL_USE_SPECULAR, self._colorFunc),
                XmlMaterialAttribute("vrayreflection_map", c4d.OCT_MATERIAL_SPECULAR_LINK, c4d.OCTANE_MATERIAL_USE_SPECULAR, self._bitmapFunc),
                XmlMaterialAttribute("reflection_map", c4d.OCT_MATERIAL_SPECULAR_LINK, c4d.OCTANE_MATERIAL_USE_SPECULAR, self._bitmapFunc),
                XmlMaterialAttribute("vrayreflection_value", c4d.OCT_MATERIAL_SPECULAR_MIX, c4d.OCTANE_MATERIAL_USE_SPECULAR, self._floatFunc, modifierFunction=self._divideBy,modifierParam=100),
                
                XmlMaterialAttribute("vrayreflection_glossiness", c4d.OCT_MATERIAL_ROUGHNESS_FLOAT, c4d.OCTANE_MATERIAL_USE_ROUGHNESS, self._floatFunc, modifierFunction=self._invertPerc),
                XmlMaterialAttribute("vrayreflection_glossiness_map", c4d.OCT_MATERIAL_ROUGHNESS_LINK, c4d.OCTANE_MATERIAL_USE_ROUGHNESS, self._bitmapFunc),
                XmlMaterialAttribute("reflection_glossiness_map", c4d.OCT_MATERIAL_ROUGHNESS_LINK, c4d.OCTANE_MATERIAL_USE_ROUGHNESS, self._bitmapFunc),
                XmlMaterialAttribute("vrayreflectionGlossiness_value", c4d.OCT_MATERIAL_ROUGHNESS_MIX, c4d.OCTANE_MATERIAL_USE_ROUGHNESS, self._floatFunc, modifierFunction=self._divideBy,modifierParam=100),
                
                XmlMaterialAttribute("vrayreflection_color", c4d.OCT_MATERIAL_REFLECTION_COLOR, c4d.OCTANE_MATERIAL_USE_REFLECTION, self._colorFunc),
                XmlMaterialAttribute("vrayreflection_map", c4d.OCT_MATERIAL_REFLECTION_LINK, c4d.OCTANE_MATERIAL_USE_REFLECTION, self._bitmapFunc),
                XmlMaterialAttribute("reflection_map", c4d.OCT_MATERIAL_REFLECTION_LINK, c4d.OCTANE_MATERIAL_USE_REFLECTION, self._bitmapFunc),
                XmlMaterialAttribute("vrayreflection_value", c4d.OCT_MATERIAL_REFLECTION_MIX, c4d.OCTANE_MATERIAL_USE_REFLECTION, self._floatFunc, modifierFunction=self._divideBy,modifierParam=100),
                
                # XmlMaterialAttribute("vrayreflection_fresnel", c4d.VRAYMATERIAL_SPECULAR1_USEFRESNEL, c4d.VRAYMATERIAL_USE_SPECULAR1, self._boolFunc),
                # XmlMaterialAttribute("vrayreflection_lockGloss", c4d.VRAYMATERIAL_SPECULAR1_LINKGLOSSINESS, c4d.VRAYMATERIAL_USE_SPECULAR1, self._boolFunc),
                #XmlMaterialAttribute("vrayreflection_ior", c4d.OCT_MATERIAL_INDEX, c4d.OCTANE_MATERIAL_USE_INDEX, self._floatFunc),
                # XmlMaterialAttribute("vrayhilight_glossiness", c4d.VRAYMATERIAL_SPECULAR1_HIGHLIGHTGLOSS, c4d.VRAYMATERIAL_USE_SPECULAR1, self._floatFunc),
                # XmlMaterialAttribute("vrayhilight_glossiness_map", c4d.VRAYMATERIAL_SPECULAR1_HIGHLIGHTGLOSSSHADER, c4d.VRAYMATERIAL_USE_SPECULAR1, self._bitmapFunc),
                # XmlMaterialAttribute("vrayhilightGlossiness_value", c4d.VRAYMATERIAL_SPECULAR1_HIGHLIGHTGLOSSTEXMULT, c4d.VRAYMATERIAL_USE_SPECULAR1, self._floatFunc, modifierFunction=self._divideBy,modifierParam=100),
                
                XmlMaterialAttribute("vrayrefraction_color", c4d.ABSORPTION_ABS, c4d.OCTANE_MATERIAL_USE_MEDIUM, self._colorToColorShaderFunc),
                #XmlMaterialAttribute("vrayrefraction_map", self.VRAY_WEIGHT_SHADER, self.VRAY_USE_WEIGHT, self._bitmapFunc),
                #XmlMaterialAttribute("refraction_map", self.VRAY_WEIGHT_SHADER, self.VRAY_USE_WEIGHT, self._bitmapFunc),
                #XmlMaterialAttribute("vrayrefraction_value", self.VRAY_REFR_TEXTUREMULT, self.VRAY_USE_WEIGHT, self._floatFunc),
                
                # XmlMaterialAttribute("vrayrefraction_affectShadows", self.VRAY_REFR_DOSHADOW, self.VRAY_USE_WEIGHT, self._boolFunc),
                # XmlMaterialAttribute("vrayrefraction_glossiness", self.VRAY_REFR_GLOSS, self.VRAY_USE_WEIGHT, self._floatFunc),
                # XmlMaterialAttribute("vrayrefraction_glossiness_map", self.VRAY_REFR_GLOSSSHADER, self.VRAY_USE_WEIGHT, self._bitmapFunc),
                # XmlMaterialAttribute("vrayrefractionGlossiness_value", self.VRAY_REFR_GLOSSTEXTUREMULT, self.VRAY_USE_WEIGHT, self._floatFunc, modifierFunction=self._divideBy,modifierParam=100),
                # XmlMaterialAttribute("vrayrefraction_ior", self.VRAY_REFR_GLOSSIOR, self.VRAY_USE_WEIGHT, self._floatFunc),
                # XmlMaterialAttribute("vrayreflection_lockIOR", None, None, self._fresnelLockFunc),
                # XmlMaterialAttribute("vraybrdf_type", c4d.VRAYMATERIAL_SPECULAR1_MODE, c4d.VRAYMATERIAL_USE_SPECULAR1, self._intFunc),
                                        ]
        
        else:
            
            self._materialStr =     {
                    #----- std_str : std_desc
                    ("specular_mode", "metal") : c4d.MATERIAL_SPECULAR_MODE_METAL,
                    ("specular_mode", "plastic") : c4d.MATERIAL_SPECULAR_MODE_PLASTIC
                                    }
            
            self._materialAttributes =  [
                    #----- Standard
                    XmlMaterialAttribute("opacity_amount", c4d.MATERIAL_ALPHA_SHADER, c4d.MATERIAL_USE_ALPHA, self._stdOpacityFunc),
                    XmlMaterialAttribute("diffuse_map", c4d.MATERIAL_COLOR_SHADER, c4d.MATERIAL_USE_COLOR, self._bitmapFunc),
                    XmlMaterialAttribute("diffusemap", c4d.MATERIAL_COLOR_SHADER, c4d.MATERIAL_USE_COLOR, self._bitmapFunc),
                    XmlMaterialAttribute("diffuse_color", c4d.MATERIAL_COLOR_COLOR, c4d.MATERIAL_USE_COLOR, self._colorFunc),
                    XmlMaterialAttribute("diffusion_brightness", c4d.MATERIAL_DIFFUSION_BRIGHTNESS, c4d.MATERIAL_USE_COLOR, self._percentFunc),
                    XmlMaterialAttribute("transparency_color", c4d.MATERIAL_TRANSPARENCY_COLOR, c4d.MATERIAL_USE_TRANSPARENCY, self._colorFunc),
                    XmlMaterialAttribute("transparency_brightness", c4d.MATERIAL_TRANSPARENCY_BRIGHTNESS, c4d.MATERIAL_USE_TRANSPARENCY, self._percentFunc),
                    XmlMaterialAttribute("bump_map", c4d.MATERIAL_BUMP_SHADER, c4d.MATERIAL_USE_BUMP, self._bitmapFunc),
                    XmlMaterialAttribute("opacity_map", c4d.MATERIAL_ALPHA_SHADER, c4d.MATERIAL_USE_ALPHA, self._bitmapFunc),
                    #Find some way to convert std Max Blend mat to std C4D..
                    XmlMaterialAttribute("mask", c4d.MATERIAL_ALPHA_SHADER, self.VRAY_USE_REFRACTION, None),
                    #XmlMaterialAttribute("material1", c4d.VRAYBLENDMATERIAL_PARAMS_LINK10, c4d.VRAYBLENDMATERIAL_PARAMS_USELINK10, self._matFunc),
                    
                                        ]
            if not self.R16:
                self._materialAttributes[len(self._materialAttributes):] =  [
                    #----- Standard Pre R16
                    XmlMaterialAttribute("specular_width", c4d.MATERIAL_SPECULAR_WIDTH, c4d.MATERIAL_USE_SPECULAR, self._percentFunc, self._specWidthFunc),
                    XmlMaterialAttribute("specularLevel", c4d.MATERIAL_SPECULAR_HEIGHT, c4d.MATERIAL_USE_SPECULAR, self._percentFunc),
                    XmlMaterialAttribute("specular_height", c4d.MATERIAL_SPECULAR_HEIGHT, c4d.MATERIAL_USE_SPECULAR, self._percentFunc),
                    XmlMaterialAttribute("specular_falloff", c4d.MATERIAL_SPECULAR_FALLOFF, c4d.MATERIAL_USE_SPECULAR, self._percentFunc),
                    XmlMaterialAttribute("specular_innerwidth", c4d.MATERIAL_SPECULAR_INNERWIDTH, c4d.MATERIAL_USE_SPECULAR, self._percentFunc),
                    XmlMaterialAttribute("specular_mode", c4d.MATERIAL_SPECULAR_MODE, c4d.MATERIAL_USE_SPECULAR, self._materialStrTypeFunc),
                    XmlMaterialAttribute("specular_color", c4d.MATERIAL_SPECULAR_COLOR, c4d.MATERIAL_USE_SPECULARCOLOR, self._colorFunc),
                    XmlMaterialAttribute("reflection_map", c4d.MATERIAL_REFLECTION_SHADER, c4d.MATERIAL_USE_REFLECTION, self._bitmapFunc),
                    XmlMaterialAttribute("vrrefraf_reflmap", c4d.MATERIAL_REFLECTION_SHADER, c4d.MATERIAL_USE_REFLECTION, self._bitmapFunc),
                                        ]
            else:
                self._materialAttributes[len(self._materialAttributes):] =  [
                    #----- Standard R16 REFLECTANCE
                    XmlMaterialAttribute("specularLevel", c4d.REFLECTION_LAYER_MAIN_VALUE_SPECULAR, c4d.MATERIAL_USE_REFLECTION, self._r16reflectance, self._percentFunc),
                    XmlMaterialAttribute("specular_height", c4d.REFLECTION_LAYER_MAIN_VALUE_SPECULAR, c4d.MATERIAL_USE_REFLECTION, self._r16reflectance, self._percentFunc),
                    XmlMaterialAttribute("specular_color", c4d.REFLECTION_LAYER_COLOR_COLOR, c4d.MATERIAL_USE_REFLECTION, self._r16reflectance, self._colorFunc),
                    XmlMaterialAttribute("specular_width", c4d.REFLECTION_LAYER_MAIN_VALUE_ROUGHNESS, c4d.MATERIAL_USE_REFLECTION, self._r16reflectance, self._floatFunc, self._invertPerc),
                    XmlMaterialAttribute("reflection_map", c4d.REFLECTION_LAYER_COLOR_TEXTURE, c4d.MATERIAL_USE_REFLECTION, self._r16reflectance, self._bitmapFunc),
                   #XmlMaterialAttribute("vrrefraf_reflmap", c4d.REFLECTION_LAYER_COLOR_TEXTURE, c4d.VRAYMATERIAL_USE_REFLECTION, self._bitmapFunc)
                                        ]
            #----- Vray -> standard
            self._materialAttributes[len(self._materialAttributes):] =  [
                XmlMaterialAttribute("vraybump_map", c4d.MATERIAL_BUMP_SHADER, c4d.MATERIAL_USE_BUMP, self._bitmapFunc),
                XmlMaterialAttribute("vraybump_value", c4d.MATERIAL_BUMP_STRENGTH, c4d.MATERIAL_USE_BUMP, self._floatFunc, modifierFunction=self._divideBy,modifierParam=100),
                XmlMaterialAttribute("vrayopacity_map", c4d.MATERIAL_ALPHA_SHADER, c4d.MATERIAL_USE_ALPHA, self._bitmapFunc),
                XmlMaterialAttribute("vrayselfillum_map", c4d.MATERIAL_LUMINANCE_SHADER, c4d.MATERIAL_USE_LUMINANCE, self._bitmapFunc),
                XmlMaterialAttribute("vrayselfillum_color", c4d.MATERIAL_LUMINANCE_COLOR, c4d.MATERIAL_USE_LUMINANCE, self._colorFunc),
                XmlMaterialAttribute("vrayselfillum_multiplier", c4d.MATERIAL_LUMINANCE_BRIGHTNESS, c4d.MATERIAL_USE_LUMINANCE, self._floatFunc),
                
                XmlMaterialAttribute("color", c4d.MATERIAL_LUMINANCE_COLOR, c4d.MATERIAL_USE_LUMINANCE, self._colorFunc),
                XmlMaterialAttribute("vraylightlightmap", c4d.MATERIAL_LUMINANCE_SHADER, c4d.MATERIAL_USE_LUMINANCE, self._bitmapFunc),
                XmlMaterialAttribute("vraylightopacitymap", c4d.MATERIAL_ALPHA_SHADER, c4d.MATERIAL_USE_ALPHA, self._bitmapFunc),
                XmlMaterialAttribute("vraylightmultiplier", c4d.MATERIAL_LUMINANCE_BRIGHTNESS, c4d.MATERIAL_USE_LUMINANCE, self._floatFunc, modifierFunction=self._divideBy, modifierParam=1),
                
                XmlMaterialAttribute("vraydiffuse_color", c4d.MATERIAL_COLOR_COLOR, c4d.MATERIAL_USE_COLOR, self._colorFunc),
                XmlMaterialAttribute("vraydiffuse_map", c4d.MATERIAL_COLOR_SHADER, c4d.MATERIAL_USE_COLOR, self._bitmapFunc),
                
             
                XmlMaterialAttribute("vrayrefraction_color", c4d.MATERIAL_TRANSPARENCY_COLOR, c4d.MATERIAL_USE_TRANSPARENCY, self._colorFunc),
                XmlMaterialAttribute("vrayrefraction_ior", c4d.MATERIAL_TRANSPARENCY_REFRACTION, c4d.MATERIAL_USE_TRANSPARENCY, self._floatFunc),
                XmlMaterialAttribute("vrayrefraction_glossiness", c4d.MATERIAL_TRANSPARENCY_DISPERSION, c4d.MATERIAL_USE_TRANSPARENCY, self._floatFunc, self._invertPerc),
                XmlMaterialAttribute("color_brightness", desc=c4d.MATERIAL_COLOR_BRIGHTNESS, use=c4d.MATERIAL_USE_COLOR, setFunction=self._percentFunc),
                XmlMaterialAttribute("color_color", desc=c4d.MATERIAL_COLOR_COLOR, use=c4d.MATERIAL_USE_COLOR, setFunction=self._colorFunc),
                XmlMaterialAttribute("specular_mode", desc=c4d.MATERIAL_SPECULAR_MODE, use=c4d.MATERIAL_USE_SPECULAR, setFunction=self._comboBoxFunc, vrayConvert=self._vrayMaterialConvert),
                #Find some way to convert VRay Max Blend mat to std C4D..
                
                #VRay Engine Environment overrides
                XmlMaterialAttribute("giMapShader", c4d.MATERIAL_LUMINANCE_SHADER, None, self._vrayEnvToStd),
                XmlMaterialAttribute("rrMapShader", c4d.MATERIAL_LUMINANCE_SHADER, None, self._vrayEnvToStd),
                
                #VRayBlend COAT BLENDAMOUNT maps [First Four Coats Only]
                XmlMaterialAttribute("coatShader0", c4d.SLA_FUSION_BLEND_CHANNEL, None, None),
                XmlMaterialAttribute("coatShader1", c4d.SLA_FUSION_BLEND_CHANNEL, None, None),
                XmlMaterialAttribute("coatShader2", c4d.SLA_FUSION_BLEND_CHANNEL, None, None),
                XmlMaterialAttribute("coatShader3", c4d.SLA_FUSION_BLEND_CHANNEL, None, None),
                
                #VRayFastSSS2 Material
                
                ###SSS COLOR FUNC###
                XmlMaterialAttribute("sss2_texmap_sss_color", c4d.XMBSUBSURFACESHADER_SHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("sss2_texmap_sss_color_multiplier", c4d.XMBSUBSURFACESHADER_STRENGTH, None, self._floatFunc),
                XmlMaterialAttribute("sss2_texmap_scatter_color", c4d.XMBSUBSURFACESHADER_DIFFUSE, None, self._colorFunc),
                XmlMaterialAttribute("sss2_texmap_scatter_radius", c4d.XMBSUBSURFACESHADER_LENGTH, None, self._bitmapFunc),
                XmlMaterialAttribute("sss2_IOR", c4d.XMBSUBSURFACESHADER_IOR, None, self._floatFunc),
                ###SSS COLOR FUNC###
                XmlMaterialAttribute("sss2_diffuse_color", c4d.MATERIAL_COLOR_COLOR, None, self._colorFunc),
                XmlMaterialAttribute("sss2_texmap_diffuse_color", c4d.MATERIAL_COLOR_SHADER, None, self._bitmapFunc),
                XmlMaterialAttribute("sss2_texmap_diffuse_amount", c4d.MATERIAL_COLOR_TEXTURESTRENGTH, None, self._floatFunc),
                XmlMaterialAttribute("sss2_texmap_bump", c4d.MATERIAL_BUMP_SHADER, c4d.MATERIAL_USE_BUMP, self._bitmapFunc),
                XmlMaterialAttribute("sss2_texmap_bump_multiplier", c4d.MATERIAL_BUMP_STRENGTH, None, self._floatFunc),
                XmlMaterialAttribute("sss2_texmap_displacement", c4d.MATERIAL_DISPLACEMENT_SHADER, c4d.MATERIAL_USE_DISPLACEMENT, self._bitmapFunc),
                
                #VRayCarPaint Material
                XmlMaterialAttribute("base_color", c4d.MATERIAL_COLOR_COLOR, c4d.MATERIAL_USE_COLOR, self._colorFunc),
                XmlMaterialAttribute("texmap_base_color", c4d.MATERIAL_COLOR_SHADER, c4d.MATERIAL_USE_COLOR, self._bitmapFunc),
                XmlMaterialAttribute("texmap_base_bump", c4d.MATERIAL_BUMP_SHADER, None, self._bitmapFunc),
                #XmlMaterialAttribute("flake_color", c4d.VRAYCARPAINTMATERIAL_FLAKECOLOR, None, self._colorFunc),
                #XmlMaterialAttribute("texmap_flake_color", c4d.VRAYCARPAINTMATERIAL_FLAKECOLORSHADER, None, self._bitmapFunc),
                #XmlMaterialAttribute("texmap_flake_glossiness", c4d.VRAYCARPAINTMATERIAL_FLAKEGLOSSINESSSHADER, None, self._bitmapFunc),
                #XmlMaterialAttribute("flake_glossiness", c4d.VRAYCARPAINTMATERIAL_FLAKEGLOSSINESS, None, self._floatFunc),
                #XmlMaterialAttribute("flake_orientation", c4d.VRAYCARPAINTMATERIAL_FLAKEORIENTATION, None, self._floatFunc),
                #XmlMaterialAttribute("texmap_flake_orientation", c4d.VRAYCARPAINTMATERIAL_FLAKEORIENTATIONSHADER, None, self._bitmapFunc),
                #XmlMaterialAttribute("flake_density", c4d.VRAYCARPAINTMATERIAL_FLAKEDENSITY, None, self._floatFunc),
                #XmlMaterialAttribute("flake_scale", c4d.VRAYCARPAINTMATERIAL_FLAKESCALE, None, self._floatFunc),
                #XmlMaterialAttribute("flake_size", c4d.VRAYCARPAINTMATERIAL_FLAKESIZE, None, self._floatFunc),
                #XmlMaterialAttribute("flake_seed", c4d.VRAYCARPAINTMATERIAL_FLAKESEED, None, self._floatFunc),
                #XmlMaterialAttribute("flake_filtering", c4d.VRAYCARPAINTMATERIAL_FLAKEFILTERING, None, self._materialStrTypeFunc),
                #XmlMaterialAttribute("flake_map_size", c4d.VRAYCARPAINTMATERIAL_FLAKEMAPSIZE, None, self._intFunc),
                #XmlMaterialAttribute("flake_mapping_type", c4d.VRAYCARPAINTMATERIAL_FLAKEMAPTYPE, None, self._materialStrTypeFunc),
                #XmlMaterialAttribute("flake_trace_reflections", c4d.VRAYCARPAINTMATERIAL_FLAKETRACEREFLECTION, None, self._boolFunc),
                #XmlMaterialAttribute("coat_color", c4d.VRAYCARPAINTMATERIAL_COATCOLOR, None, self._colorFunc),
                #XmlMaterialAttribute("texmap_coat_color", c4d.VRAYCARPAINTMATERIAL_COATCOLORSHADER, None, self._bitmapFunc),
                #XmlMaterialAttribute("coat_strength", c4d.VRAYCARPAINTMATERIAL_COATSTRENGTH, None, self._floatFunc),
                #XmlMaterialAttribute("texmap_coat_strength", c4d.VRAYCARPAINTMATERIAL_COATSTRENGTHSHADER, None, self._bitmapFunc),
                #XmlMaterialAttribute("coat_glossiness", c4d.VRAYCARPAINTMATERIAL_COATGLOSSINESS, None, self._floatFunc),
                #XmlMaterialAttribute("texmap_coat_glossiness", c4d.VRAYCARPAINTMATERIAL_COATGLOSSINESSSHADER, None, self._bitmapFunc),
                #XmlMaterialAttribute("coat_trace_reflections", c4d.VRAYCARPAINTMATERIAL_COATTRACEREFLECTIONS, None, self._boolFunc),
                #XmlMaterialAttribute("texmap_coat_bump", c4d.VRAYCARPAINTMATERIAL_COATBUMPSHADER, None, self._bitmapFunc),
                #XmlMaterialAttribute("trace_reflections", c4d.VRAYCARPAINTMATERIAL_TRACEREFLECTIONS, None, self._boolFunc),
                #XmlMaterialAttribute("double_sided", c4d.VRAYCARPAINTMATERIAL_DOUBLESIDED, None, self._boolFunc),
                #XmlMaterialAttribute("subdivs", c4d.VRAYCARPAINTMATERIAL_SUBDIVS, None, self._intFunc),
                #XmlMaterialAttribute("cutoff_threshold", c4d.VRAYCARPAINTMATERIAL_CUTOFF, None, self._floatFunc),
                #XmlMaterialAttribute("environment_priority", c4d.VRAYCARPAINTMATERIAL_ENVPRIORITY, None, self._intFunc),
                #XmlMaterialAttribute("texmap_environment_override", c4d.VRAYCARPAINTMATERIAL_ENVOVERRIDESHADER, None, self._bitmapFunc),
                                                                        ]
            if not self.R16:
                self._materialAttributes[len(self._materialAttributes):] =  [
                    XmlMaterialAttribute("vrayreflection_color", c4d.MATERIAL_REFLECTION_COLOR, c4d.MATERIAL_USE_REFLECTION, self._colorFunc),
                    XmlMaterialAttribute("vrayreflection_map", c4d.MATERIAL_REFLECTION_SHADER, c4d.MATERIAL_USE_REFLECTION, self._bitmapFunc),
                    XmlMaterialAttribute("vrayreflection_glossiness", c4d.MATERIAL_REFLECTION_DISPERSION, c4d.MATERIAL_USE_REFLECTION, self._floatFunc, self._invertPerc),
                    XmlMaterialAttribute("vrayhilight_glossiness", c4d.MATERIAL_SPECULAR_WIDTH, c4d.MATERIAL_USE_SPECULAR, self._floatFunc),
                    XmlMaterialAttribute("vrayreflection_lockGloss", self.STD_LOCKGLOSS, None, self._boolFunc),
                    XmlMaterialAttribute("texmap_base_reflection", c4d.MATERIAL_REFLECTION_SHADER, c4d.MATERIAL_USE_REFLECTION, self._bitmapFunc),
                    XmlMaterialAttribute("base_glossiness", c4d.MATERIAL_REFLECTION_DISPERSION, c4d.MATERIAL_USE_REFLECTION, self._floatFunc, self._invertPerc),
                    XmlMaterialAttribute("vrayreflection_fresnel", c4d.MATERIAL_REFLECTION_SHADER, c4d.MATERIAL_USE_REFLECTION, self._r15fresnel),
                    
                    XmlMaterialAttribute("sss2_specular_color", c4d.MATERIAL_SPECULAR_COLOR, None, self._colorFunc),
                    XmlMaterialAttribute("sss2_specular_amount", c4d.MATERIAL_SPECULAR_HEIGHT, None, self._floatFunc),
                    XmlMaterialAttribute("sss2_texmap_specular_color", c4d.MATERIAL_SPECULAR_SHADER, None, self._bitmapFunc),
                    XmlMaterialAttribute("sss2_specular_glossiness", c4d.MATERIAL_SPECULAR_WIDTH, None, self._floatFunc),
                    #Find some way to convert VRay Max Blend mat to std C4D..
                                                                            ]
            else:
                self._materialAttributes[len(self._materialAttributes):] =  [
                    #XmlMaterialAttribute("vrayreflection_fresnel", c4d.REFLECTION_LAYER_FRESNEL_MODE, c4d.MATERIAL_USE_REFLECTION, self._r16reflectance, self._boolAsInt),
                    XmlMaterialAttribute("vrayreflection_ior", c4d.REFLECTION_LAYER_FRESNEL_VALUE_IOR, c4d.MATERIAL_USE_REFLECTION, self._r16reflectance, self._floatFunc),
                    XmlMaterialAttribute("vrayreflection_color", c4d.REFLECTION_LAYER_COLOR_COLOR, c4d.MATERIAL_USE_REFLECTION, self._r16reflectance, self._colorFunc),
                    XmlMaterialAttribute("vrayreflection_map", c4d.REFLECTION_LAYER_COLOR_TEXTURE, c4d.MATERIAL_USE_REFLECTION, self._r16reflectance, self._bitmapFunc),
                    XmlMaterialAttribute("vrayreflection_glossiness", c4d.REFLECTION_LAYER_MAIN_VALUE_ROUGHNESS, c4d.MATERIAL_USE_REFLECTION, self._r16reflectance, self._floatFunc, self._invertPerc),
                    #XmlMaterialAttribute("vrayhilight_glossiness", c4d.REFLECTION_LAYER_MAIN_VALUE_ROUGHNESS, None, self._r16reflectance, self._floatFunc, self._invertPerc),
                    #XmlMaterialAttribute("vrayreflection_lockGloss", self.STD_LOCKGLOSS, None, self._r16reflectance, self._boolFunc),
                    XmlMaterialAttribute("texmap_base_reflection", c4d.REFLECTION_LAYER_COLOR_TEXTURE, c4d.MATERIAL_USE_REFLECTION, self._r16reflectance, self._bitmapFunc),
                    XmlMaterialAttribute("base_glossiness", c4d.REFLECTION_LAYER_MAIN_VALUE_ROUGHNESS, None, self._r16reflectance, self._floatFunc, self._invertPerc),
                    
                    XmlMaterialAttribute("sss2_texmap_specular_color", c4d.REFLECTION_LAYER_COLOR_TEXTURE, c4d.MATERIAL_USE_REFLECTION, self._r16reflectance, self._bitmapFunc),
                    XmlMaterialAttribute("sss2_specular_color", c4d.REFLECTION_LAYER_COLOR_COLOR, c4d.MATERIAL_USE_REFLECTION, self._r16reflectance, self._colorFunc),
                    #XmlMaterialAttribute("sss2_specular_glossiness", c4d.REFLECTION_LAYER_MAIN_VALUE_ROUGHNESS, None, self._r16reflectance, self._floatFunc, self._invertPerc),
                    #Find some way to convert VRay Max Blend mat to std C4D..
                                                                            ]
    
    #----------------------- Set Functions -------------------------------------
    
    def _stdIESFilenameAndEnable(self,attribute,data,op):
        if (self._vrayMaterials):
            op[c4d.VRAYLIGHTTAG_IES_ON] = True
            op[c4d.VRAYLIGHTTAG_IES_FILE] = str(data)
        else:
            op[c4d.LIGHT_PHOTOMETRIC_DATA] = True
            op[c4d.LIGHT_PHOTOMETRIC_UNITS] = True
            op[c4d.LIGHT_PHOTOMETRIC_FILE] = str(data)
        
    def _displacementTypeFunc(self,attribute,data,op):
        #if int(data)==2:
            #op[c4d.VRAYDISPLACEMATERIAL_USESUBD] = True
        if int(data)==0:
            op[attribute.desc] =1
        elif int(data)==1:
            op[attribute.desc] =0
    
    def _ccLevelFunc(self,attribute,data,op):
        if float(data)>0:
            op[attribute.desc] = (float(data)/100.0)*0.5
        else:
            op[attribute.desc] = float(data)/100.0
    
    def _ccContrastFunc(self,attribute,data,op):
        if float(data)>0:
            op[attribute.desc] = 0.5+((float(data)/100.0)*0.5)
        elif float(data)<0:
            op[attribute.desc] = ((float(data)*-1)/100.0)*0.5
    
    def _percToColor(self,attribute,data,op):
        val = float(data)/100.0
        op[attribute.desc] = c4d.Vector(val,val,val)
    
    def _aoGradFunc(self,attribute,data,op):
        if (attribute.shaderName=="vrdirt_occludedColor"):
            grad = c4d.Gradient()
            components = data.split(" ")
            data = c4d.Vector(float(components[0]), float(components[1]), float(components[2])) / 255.0
            grad.InsertKnot(col=data,pos=0,brightness=1)
            op[c4d.AMBIENTOCCLUSIONSHADER_GRADIENT] = grad
        elif (attribute.shaderName=="vrdirt_unoccludedColor"):
            grad = c4d.Gradient()
            components = data.split(" ")
            data = c4d.Vector(float(components[0]), float(components[1]), float(components[2])) / 255.0
            ograd = op[c4d.AMBIENTOCCLUSIONSHADER_GRADIENT]
            colr = ograd.GetKnot(0)['col']
            grad.InsertKnot(col=colr,pos=0,brightness=1)
            grad.InsertKnot(col=data,pos=1,brightness=1)
            op[c4d.AMBIENTOCCLUSIONSHADER_GRADIENT] = grad
        op.Message(c4d.MSG_UPDATE)
    
    def _vrayMappingAdaptionFunc(self,attribute,data,op):
        """Set Vray Adaption On/Off.
        """
        try:
            if self._vrayMaterials:
                if str(data)=="None":
                    op[c4d.VP_VRAYBRIDGE_COLORMAPPING_ADAPTATION] = True
                    op[c4d.VP_VRAYBRIDGE_COLORMAPPING_ADAPTATION_NOVIEWPORT] = True
                elif str(data)=="Color mapping and gamma":
                    op[c4d.VP_VRAYBRIDGE_COLORMAPPING_GAMMA] = 2.2
                else:
                    #If Gamma hasn't been set to the above 2.2 then set to XML value as normal..
                    if attribute.desc==c4d.VP_VRAYBRIDGE_COLORMAPPING_GAMMA:
                        if op[c4d.VP_VRAYBRIDGE_COLORMAPPING_GAMMA] != 2.2:
                            op[c4d.VP_VRAYBRIDGE_COLORMAPPING_GAMMA] = int(data)
        except KeyError:
            print attribute.name + " cannot be set to " + str(data)
    
    def _vrayPortalLightFunc(self,attribute,data,op):
        if data=="true":
            if op[attribute.desc] == 1:
                op[attribute.desc] = 2
            else:
                op[attribute.desc] = 1
    
    def _pathFunc(self,attribute,data,op):
        bc = op.GetDataInstance()
        bc.SetFilename(attribute.desc,str(data))
    
    def _stdOpacityFunc(self, attribute, data, op):
        if float(data) < 100:
            if self._vrayMaterials:
                colorShader = c4d.BaseShader(5832)
                colorShader[c4d.COLORSHADER_COLOR] = c4d.Vector(0,0,0)
                op.InsertShader(colorShader)
                op[self.VRAY_WEIGHT_SHADER] = colorShader
                op[self.VRAY_REFR_TEXTUREMULT] = float(data)/100
            else:
                colorShader = c4d.BaseShader(5832)
                val = float(data)/100
                colorShader[c4d.COLORSHADER_COLOR] = c4d.Vector(val,val,val)
                op.InsertShader(colorShader)
                op[c4d.MATERIAL_ALPHA_SHADER] = colorShader
        else:
            if self._vrayMaterials:
                op[self.VRAY_USE_REFRACTION] = False
            else:
                op[c4d.MATERIAL_USE_ALPHA] = False
    
    def _stdShutterFunc(self, attribute, data, op):
        op[attribute.desc] = 1/float(data)
    
    def _matFunc(self, attribute, data, op):
        if ":" in data:
            data = str(data[0:data.index(":")])
        mats = self._GetMaterials(data)
        if len(mats) != 0:
            for mat in mats:
                if mat.GetName() != op.GetName():
                    op[attribute.desc] = mat
    
    def _r15fresnel(self, attribute, data, op, node):
        if data=="true":
            fresnelShader = c4d.BaseShader(1011103)
            fresnelShader[c4d.SLA_FRESNEL_PHY_ENABLE] = True
            if node.hasAttribute("vrayreflection_lockIOR"):
                if node.getAttribute("vrayreflection_lockIOR") == "true":
                    if node.hasAttribute("vrayrefraction_ior"):
                        ior = node.getAttribute("vrayrefraction_ior")
                else: 
                    if node.hasAttribute("vrayreflection_ior"):
                        ior = node.getAttribute("vrayreflection_ior")
            fresnelShader[c4d.SLA_FRESNEL_PHY_IOR] = float(ior)
            if op[c4d.MATERIAL_REFLECTION_SHADER] == None:
                op.InsertShader(fresnelShader)
                op[c4d.MATERIAL_REFLECTION_SHADER] = fresnelShader
                op[c4d.MATERIAL_REFLECTION_TEXTUREMIXING] = 3
            else:
                blendShader = c4d.BaseShader(1011109)
                blendShader.InsertShader(fresnelShader)
                blendShader[c4d.SLA_FUSION_BASE_CHANNEL] = op[c4d.MATERIAL_REFLECTION_SHADER]
                blendShader[c4d.SLA_FUSION_BLEND_CHANNEL] == fresnelShader
                blendShader[c4d.SLA_FUSION_BLEND] = 1
                blendShader[c4d.SLA_FUSION_MODE] = 2019
                op.InsertShader(blendShader)
            
            specfresnelShader = c4d.BaseShader(1011103)
            specfresnelShader[c4d.SLA_FRESNEL_PHY_ENABLE] = True
            specfresnelShader[c4d.SLA_FRESNEL_PHY_IOR] = float(ior)
            if op[c4d.MATERIAL_SPECULAR_SHADER] == None:
                op.InsertShader(specfresnelShader)
                op[c4d.MATERIAL_SPECULAR_SHADER] = specfresnelShader
                op[c4d.MATERIAL_SPECULAR_TEXTUREMIXING] = 3
            else:
                specblendShader = c4d.BaseShader(1011109)
                specblendShader.InsertShader(specfresnelShader)
                specblendShader[c4d.SLA_FUSION_BASE_CHANNEL] = op[c4d.MATERIAL_SPECULAR_SHADER]
                specblendShader[c4d.SLA_FUSION_BLEND_CHANNEL] == specfresnelShader
                specblendShader[c4d.SLA_FUSION_BLEND] = 1
                specblendShader[c4d.SLA_FUSION_MODE] = 2019
                op.InsertShader(specblendShader)
     
    def _fusionSpeckleFunc(self, attribute, data, fusionShader):
        """Set percent attribute.
        """
        if attribute.shaderName=="speckle_size":
            if fusionShader[c4d.SLA_FUSION_MASK_CHANNEL] == None:
                noiseShader = c4d.BaseShader(1011103)
                noiseShader[c4d.SLA_NOISE_GLOBAL_SCALE] = data
                noiseShader[c4d.SLA_NOISE_NOISE] = 2031
                fusionShader.InsertShader(noiseShader)
                fusionShader[c4d.SLA_FUSION_MASK_CHANNEL] = noiseShader
                fusionShader[c4d.SLA_FUSION_USE_MASK] = True
        else:
            attribute.modifierFunction(attribute,data,fusionShader)
         
    def _fusionFalloffFunc(self, attribute, data, fusionShader):
        """Set percent attribute.
        """
        if attribute.shaderName=="fallof_type" or attribute.shaderName=="falloff_direction" or attribute.shaderName=="falloff_ior" or attribute.shaderName=="falloff_mtlIOROverride":
            if fusionShader[c4d.SLA_FUSION_MASK_CHANNEL] == None:
                fresnelShader = c4d.BaseShader(1011103)
                fusionShader.InsertShader(fresnelShader)
                fusionShader[c4d.SLA_FUSION_MASK_CHANNEL] = fresnelShader
                fusionShader[c4d.SLA_FUSION_USE_MASK] = True
            tempAttr = XmlShaderAttribute(shaderName=attribute.shaderName, desc=attribute.desc, setFunction=attribute.setFunction, modifierFunction=None, vrayAttribute=False)
            attribute.modifierFunction(tempAttr,data,fusionShader[c4d.SLA_FUSION_MASK_CHANNEL])
        else:
            attribute.modifierFunction(attribute,data,fusionShader)
        
    def _r16reflectance(self, attribute, data, op):
        if (attribute.name=="specular_width"):
            if (self.R16):
                data = float(data) / 100
        base = c4d.REFLECTION_LAYER_LAYER_DATA + c4d.REFLECTION_LAYER_LAYER_SIZE * self.REFLECTION_LAYERID #Imported Specular Layer
        attribute.desc = base+int(attribute.desc)
        attribute.setFunction = attribute.modifierFunction
        attribute.modifierFunction = attribute.modifierParam
        modifierParam = None
        attribute.setFunction(attribute, data, op)
    
    def _specWidthFunc(self, attribute, data):
        """Convert max spec width to c4d .
        """
        x = 100-(data*100.0)
        y = 34 - (81*x/50) + (23*x**2/625) - (x**3/6250)
        return y/100.0
    
    def _fresnelLockFunc(self, attribute, data, op):
        """Convert max spec width to c4d .
        """
        if str(data).lower() == "true":
            op[c4d.VRAYMATERIAL_SPECULAR1_FRESNELIOR1] = op[self.VRAY_REFR_GLOSSIOR]
        
    def _cellNoiseClampFunc(self, attribute, data, op):
        op[c4d.SLA_NOISE_LOW_CLIP] = 0.25
        op[c4d.SLA_NOISE_HIGH_CLIP] = 0.40
        #op[c4d.SLA_NOISE_GLOBAL_SCALE] *= 2.5
        op[c4d.SLA_NOISE_NOISE] = 2027
    
    def _percentFunc(self, attribute, data, op):
        """Set percent attribute.
        """
        if attribute.modifierFunction is None:
            op[attribute.desc] = int(data) / 100.0
        else:
            op[attribute.desc] = attribute.modifierFunction(attribute, int(data) / 100.0)
    
    def _setActiveCam(self, attribute, data, op):
        if str(data).lower() == "true":
            if op.GetType()==5103:
                self._doc.GetActiveBaseDraw().SetSceneCamera(op)
        
    def _floatFunc(self, attribute, data, op):
        """Set int attribute.
        """
        if attribute.modifierFunction is None:
            op[attribute.desc] = float(data)
        else:
            op[attribute.desc] = attribute.modifierFunction(attribute, float(data))
    
    def _floatFuncDivDiez(self, attribute, data, op):
        """Set int attribute.
        """
        if attribute.modifierFunction is None:
            op[attribute.desc] = float(data)/10
        else:
            op[attribute.desc] = attribute.modifierFunction(attribute, float(data))/10
    
    def _floatFuncDivCien(self, attribute, data, op):
        """Set int attribute.
        """
        if attribute.modifierFunction is None:
            op[attribute.desc] = float(data)/100
        else:
            op[attribute.desc] = attribute.modifierFunction(attribute, float(data))/100

    def _sunIntensityFunc(self, attribute, data, op):
        """Set int attribute.
        """
        op[c4d.VRAYLIGHTTAG_SUN_HORIZILLUM_PHYCAM] = 25000*float(data)
        op[c4d.VRAYLIGHTTAG_SUN_HORIZILLUM_STDCAM] = 250*float(data)
        op[c4d.VRAYLIGHTTAG_SUN_PHYINTMUL] = (100*float(data))/100
        op[c4d.VRAYLIGHTTAG_SUN_STDINTMUL] = (3.75*float(data))/100
    
    def _hueShiftFunc(self, attribute, data, op):
        """Set int attribute.
        """
        if not self._vrayMaterials:
            if float(data)<0:
                data = 360-(float(data)*(-1.0))    
            op[attribute.desc] = self._angleToRad(attribute, float(data))
        else:
            # op[attribute.desc] = float(data)
            if float(data)<0:
                data = 360-(float(data)*(-1.0))    
            op[attribute.desc] = self._angleToRad(attribute, float(data))
    
    def _setLightIntensityUnit(self, attribute, data, op):
        """Set int attribute.
        """
        op.GetObject()[c4d.LIGHT_PHOTOMETRIC_UNIT] = 0
        op.GetObject()[attribute.desc] = float(data) *150
    
    def _vrayLightUnitConversion(self, attribute, data, op):
        if data=="Luminous ower (lm)":
            if self._vrayMaterials:
                op[c4d.VRAYLIGHTTAG_COMMON_INTENSITY] = op[c4d.VRAYLIGHTTAG_COMMON_INTENSITY] / 100
                op.GetObject()[c4d.LIGHT_PHOTOMETRIC_INTENSITY] = op[c4d.VRAYLIGHTTAG_COMMON_INTENSITY] * 150
            else:
                op[c4d.LIGHT_BRIGHTNESS] /= 100
    
    def _floatFuncTagParent(self, attribute, data, op):
        """Set int attribute.
        """
        if attribute.modifierFunction is None:
            op.GetObject()[attribute.desc] = float(data)
        else:
            op.GetObject()[attribute.desc] = attribute.modifierFunction(attribute, float(data))
    
    def _intFunc(self, attribute, data, op):
        """Set int attribute.
        """
        if attribute.modifierFunction is None:
            try:
                op[attribute.desc] = int(data)
            except AttributeError:
                pass
        else:
            op[attribute.desc] = attribute.modifierFunction(attribute, int(data))

    def _intFuncDiv100(self, attribute, data, op):
        """Set int attribute.
        """
        if attribute.modifierFunction is None:
            try:
                op[attribute.desc] = int(data)/100
            except AttributeError:
                pass
        else:
            op[attribute.desc] = attribute.modifierFunction(attribute, int(data)/100)
    
    def _intFuncPut1(self, attribute, data, op):
        """Set int attribute.
        """
        if attribute.modifierFunction is None:
            try:
                op[attribute.desc] = 1
            except AttributeError:
                pass
        else:
            op[attribute.desc] = 1
    
    def _invertBool(self, attribute, data, op):
        """Set bool attribute.
        """
        try:
            if str(data).lower() == "true":
                op[attribute.desc] = 0
            else:
                op[attribute.desc] = 1
        except IndexError:
            pass

    def _boolAsInt(self, attribute, data, op):
        if data == "true":
            data = 1
        else:
            data = 0
        op[attribute.desc] = int(data)
        
    def _strFunc(self, attribute, data, op):
        """Set str attribute.
        """
        op[attribute.desc] = str(data)
    
    def _boolFuncTagParent(self, attribute, data, op):
        """Set bool attribute.
        """
        try:
            if str(data).lower() == "true":
                op.GetObject()[attribute.desc] = True
            else:
                op.GetObject()[attribute.desc] = False
        except c4d.AttributeError:
            pass
    
    def _truefalseToBool(self, data):
        if str(data).lower() == "true":
            return True
        else:
            return False
    
    def _boolFunc(self, attribute, data, op):
        """Set bool attribute.
        """
        try:
            if str(data).lower() == "true":
                op[attribute.desc] = True
            else:
                op[attribute.desc] = False
        except IndexError:
            pass
    
    def _mixMaskEnabledFunc(self, attribute, data, op):
        """Set bool attribute.
        """
        try:
            if str(data).lower() == "true":
                op[attribute.desc] = True
                op[c4d.SLA_FUSION_BLEND] = 100
            else:
                op[attribute.desc] = False
        except IndexError:
            pass
    
    def _vrayShaderPath(self, attribute, path, shader):
        # print "------------------------------------------"
        #print "----------VRAYSHADERPATH FUNC-------------"
        # print "------------------------------------------"
        #To set and update the bitmap in a VRay shader, a special bit of fuckery is required
        print("Shader === "+str(shader[c4d.VRAY_SHADERS_LIST]))
        l=0
        while l<11:
            try:
                shader[c4d.VRAY_SHADERS_LIST] = l
                if shader[4997] == "TexXSIBitmap":
                    break
            except AttributeError:
                pass
            l+=1
        shader.Message(c4d.MSG_CHANGE);
        try:
            shader[4999] = str(path)
            shader[89981969] = 0.454545
            bc = shader.GetDataInstance()
            bc[89981969] = 0.454545
            bc.SetFilename(4999,path)
        except AttributeError:
            shader.SetFilename(4999,path)
            shader[89981969] = 0.454545
        shader.Message(c4d.MSG_CHANGE);
        c4d.EventAdd()
	
    def _vrBlendSubmatFunc(self, attribute, matName, op):
        #Check all materials in all xml material type lists, then search for the actual scene name and assign that material
        
        # matLists = ["material","overridematerial","twosidedmaterial","blendmaterial"]
        # for i in xrange(len(matLists)):
            # nodes = self._GetNodes(self._data, matLists[i])
            # for node in nodes:
                # if node.getAttribute("name")==matName:
                    # if self._vrayMaterials:
                        # if matLists[i] == "material":
                            # sceneMatName = "VR_"+node.getAttribute("name")
                        # elif matLists[i] == "overridematerial":
                            # sceneMatName = "VR_OVERRIDE"+node.getAttribute("name")
                        # elif matLists[i] == "twosidedmaterial":
                            # sceneMatName = "VR_TWOSIDED"+node.getAttribute("name")
                        # elif matLists[i] == "blendmaterial":
                            # sceneMatName = "VR_BLEND"+node.getAttribute("name")
                    # else:
                        # sceneMatName = node.getAttribute("name")
                    # sceneMats = self._doc.GetMaterials()
                    # for mat in sceneMats:
                        # if mat.GetName()==sceneMatName:
                            # op[attribute.desc] = mat
                            
        mats = self._GetMaterials(matName)
        if len(mats) >0:
            op[attribute.desc] = mats[0]
    
    def _vrWrapperSubmatFunc(self, attribute, matName, op):
        mats = self._GetMaterials(matName)
        try:
            mats[0].SetName(op.GetName())
        except IndexError:
            pass
        op.SetName("emptyWrapper")
    
    def _vrayEnvToStd(self, attribute, data, op):
        print "_vrayEnvToStd.."
        
    def _dirtBiasFunc(self, attribute, data, op):
        vecString = data[1:len(data)-1].split(",",3)
        op[220264373] = float(vecString[0])
        op[220264374] = float(vecString[1])
        op[220264375] = float(vecString[2])
    
    def _bitmapShaderFunc(self, attribute, data, op):
        # print "------------------------------------------"
        # print "----------BITMAPSHADER FUNC---------------"
        # print "------------------------------------------"
        """Set bitmap shader attribute.
        """ 
        if attribute.shaderName=="filename" or attribute.shaderName=="Path"  or attribute.shaderName=="HDRIMapName":
            if self._usingOctane:
                op[c4d.IMAGETEXTURE_FILE] = str(data)
                op[c4d.IMAGETEXTURE_MODE] = 0
                op[c4d.IMAGETEXTURE_GAMMA] = 2.2
                op[c4d.IMAGETEX_BORDER_MODE] = 0
            try:
                op.SetFilename(c4d.BITMAPSHADER_FILENAME, str(data))
                op[c4d.BITMAPSHADER_COLORPROFILE] = 2
                #op[c4d.BITMAPSHADER_EXPOSURE] = -0.45
            except AttributeError:
                bc = op.GetData()
                bc.SetFilename(c4d.BITMAPSHADER_FILENAME, str(data))
                op.SetData(bc)
                #op[c4d.BITMAPSHADER_EXPOSURE] = -0.45
                op[c4d.BITMAPSHADER_COLORPROFILE] = 2
    
    def _bitmapFunc(self, attribute, data, op):
        # print "------------------------------------------"
        print "----------BITMAP FUNC---------------------"
        # print "------------------------------------------"
        """Set bitmap shader attribute.
        """ 
        if (self.CB_UP_CURRENT):
            print "setting bitmap.."
            bitmap = c4d.BaseList2D(c4d.Xbitmap)
            bitmap[c4d.BITMAPSHADER_FILENAME] = str(data)
            op.InsertShader(bitmap)
            op[attribute.desc] = bitmap
            
    def _shaderFunc(self, attribute, shaderType, op, vray):
        """Set shader attribute.
        """
        if len(str(shaderType))>=3:
            vray=False #If its stored as a vray shader but actually uses std c4d params then set as std shader
        if vray:
            shader = c4d.BaseList2D(self.VRAYSHADER)
            # l=0
            # while l<111:
                # try:
                    # shader[c4d.VRAY_SHADERS_LIST] = l
                    # if shader[c4d.VRAY_SHADERS_LIST] == shaderType:
                        # break
                # except AttributeError:
                    # pass
                # l+=1
            shader[c4d.VRAY_SHADERS_LIST] = int(shaderType)
            for shaderAttr in self._vrayShaderAttributes:
                #If the vray shader auto creates any sub shaders, remove them
                if shaderAttr.setFunction == self._bitmapFunc:
                    if shader[shaderAttr.desc] is not None:
                        #print "TYPE = "+str(shader[shaderAttr.desc].GetCustomDataTypeDefault())
                        try:
                            shader[shaderAttr.desc] = None
                        except TypeError:
                            pass
        else:
            try:
                shader = c4d.BaseList2D(shaderType)
            except StandardError:
                shader = c4d.BaseList2D(5832) #Substitue with c4d Color shader
        
        op.InsertShader(shader)
        try:
            op[attribute.desc] = shader
            #print "ShaderFunc = "+str(op)+" [ "+str(attribute.desc)+" ] = "+str(op[attribute.desc])
        except TypeError:
            #print "Cannot set "+attribute.name+" with "+str(shader)
            op[attribute.desc] = shader
        shader.Message(c4d.MSG_CHANGE);
        return shader
    
    def _utilityShaderFunc(self, desc, shaderType, op, vray):
        """Set shader for render setting attribute.
        """
        #shader = c4d.BaseList2D(shaderType)
        if vray:
            # shader = c4d.BaseList2D(self.VRAYSHADER)
            # shader[c4d.VRAY_SHADERS_LIST] = shaderType
            shader = c4d.BaseList2D(shaderType)
        else:
            shader = c4d.BaseList2D(shaderType)
        op.InsertShader(shader)
        op[desc] = shader
        return shader
    
    def _colorFunc(self, attribute, data, op):
        """Set color attribute.
        """
        components = data.split()
        color = c4d.Vector(int(components[0]), int(components[1]), int(components[2])) / 255.0
        op[attribute.desc] = color
    
    def _cellColorFunc(self, attribute, data, op):
        """Set color attribute.
        """
        components = data.split()
        color = c4d.Vector(int(components[0]), int(components[1]), int(components[2])) / 255.0
        colorO = op[c4d.SLA_NOISE_COLOR1]
        #Guessing which cell color to use, as max cellular uses two div colors plus a cell color, the first div color actually shows as cells and affects the look of it, so if the first cell color is V ( brighter ) than the actual already assigned cell color, then use that instead - its a compromise.
        if (c4d.utils.RGBToHSV(color)[2]>c4d.utils.RGBToHSV(colorO)[2]):
            op[attribute.desc] = color
    
    def _colorToColorShaderFunc(self, attribute, data, op):
        """Set color attribute.
        """
        components = data.split()
        if self._usingOctane:
            colorShader = c4d.BaseShader(1029504)
            colorShader[c4d.RGBSPECTRUMSHADER_COLOR] = c4d.Vector(int(components[0]), int(components[1]), int(components[2]))
        else:
            colorShader = c4d.BaseShader(5832)
            colorShader[c4d.COLORSHADER_COLOR] = c4d.Vector(int(components[0]), int(components[1]), int(components[2])) / 255.0
        op.InsertShader(colorShader)
        op[attribute.desc] = colorShader
    
    def _colorFuncTagParent(self, attribute, data, op):
        """Set color attribute.
        """
        components = data.split()
        op.GetObject()[attribute.desc] = c4d.Vector(int(components[0]), int(components[1]), int(components[2])) / 255.0
    
    def _comboBoxFunc(self, attribute, data, op):
        """Set combo box attribute.
        """
        op[attribute.desc] = int(data)
      
    def _lightStrTypeFunc(self, attribute, data, op):
        """Set string type attribute.
        """
        try:
            if self._vrayLights:
                op[attribute.desc] = self._vrayLightStr[(attribute.name, str(data).lower())][0]
            else:
                if self._quickMode:
                    if str(data.lower())=="area":
                        data = "shadowmap"
                op[attribute.desc] = self._lightStr[(attribute.name, str(data).lower())]
        except KeyError:
            print attribute.name + " cannot be set to " + str(data)
    
    def _shaderStrTypeFunc(self, attribute, data, op):
        """Set string type attribute.
        """
        try:
            if self._vrayMaterials:
                for shaderStr in self._shaderStr:
                    if data==shaderStr.name:
                        newStr = shaderStr
                        if attribute.shaderName == "noise_type":
                            if attribute.desc==c4d.SLA_NOISE_NOISE:                            
                                newStr.desc = 2013
                            else:
                                newStr.desc = 0
                        if attribute.shaderName[0:len(attribute.shaderName)-1] == "composite_blendMode":
                            if data=="Normal":
                                newStr.desc = 2001
                        op[attribute.desc] = newStr.desc
            else:
                for shaderStr in self._shaderStr:
                    if data==shaderStr.name:
                        op[attribute.desc] = shaderStr.desc
                #op[attribute.desc] = self._shaderStr[(attribute.name, int(data))]
        except KeyError:
            print attribute.name + " cannot be set to " + str(data)
    
    def _fallshaderStrTypeFunc(self, attribute, data, op):
        """Set string type attribute.
        """
        try:
            if self._vrayMaterials:
                for shaderStr in self._shaderStr:
                    if data==shaderStr.name:
                        if shaderStr.name == "Fresnel":
                            op[attribute.desc] = 2
                        elif shaderStr.name == "Shadow/Light":
                            op[attribute.desc] = 3
                        elif shaderStr.name == "Perpendicular/Parallel":
                            op[attribute.desc] = 1
                        else:
                            op[attribute.desc] = 0
            else:
                for shaderStr in self._shaderStr:
                    if data==shaderStr.name:
                        op[attribute.desc] = shaderStr.desc
                #op[attribute.desc] = self._shaderStr[(attribute.name, int(data))]
        except KeyError:
            print attribute.name + " cannot be set to " + str(data)
            
    def _gradShaderStrTypeFunc(self, attribute, data, op):
        if self._vrayMaterials:
            if attribute.shaderName=="ramp_noiseType" and data=="Regular":
                op[c4d.SLA_GRADIENT_OCTAVES] = 1.0
        else:
            if attribute.shaderName=="ramp_noiseType" and data=="Regular":
                op[c4d.SLA_GRADIENT_OCTAVES] = 1.0
    
    def _materialStrTypeFunc(self, attribute, data, op):
        """Set string type attribute.
        """
        try:
            if self._vrayMaterials:
                op[attribute.desc] = self._vrayMaterialStr[(attribute.name, str(data).lower())][0]
            else:
                op[attribute.desc] = self._materialStr[(attribute.name, str(data).lower())]
        except KeyError:
            print attribute.name + " cannot be set to " + str(data)

    def _renderStrTypeFunc(self, attribute, data, op):
          """Set string type attribute.
          """
          try:
              if self._vrayMaterials or self._vrayLights:
                  op[attribute.desc] = self._vrayRenderStr[(attribute.name, str(data))]
          except KeyError:
              print attribute.name + " cannot be set to " + str(data)
    
    def _docNameFunc(self,attribute, name, op):
        self._doc.SetDocumentName(name)
    
    def _importModeFunc(self,attribute, data, op):
        self._importRenderMode = data.lower()
    
    def _renderEngineFunc(self, attribute, data, op):
        """Set render engine type attribute.
        """
        for engine in self._renderEngines.keys():
            if self._vrayLights or self._vrayMaterials:
                print "Setting Renderer = VRAY"
                #Either way, set Vray if Vray Option has been chosen..
                vp = self._GetVrayVideoPost(self._doc.GetActiveRenderData())
                if vp:
                  vp.SetName("VrayBridge")
                  op[attribute.desc] = self.VRAYBRIDGE #self._renderEngines[engine]
            elif self._usingOctane:
                print "Setting Renderer = OCTANE"
                #Set Octane if Octane Option has been chosen..
                vp = self._GetOctaneVideoPost(self._doc.GetActiveRenderData())
                if vp:
                  vp.SetName("Octane Renderer")
                  op[attribute.desc] = self.OCTANE #self._renderEngines[engine]
                  
    def _resolutionFunc(self, attribute, data, op):
        """Set resolution attribute.
        """
        components = data.split(',')
        op[c4d.RDATA_LOCKRATIO] = True #Set LockRatio On#
        op[attribute.desc[0]] = int(components[0])
        op[attribute.desc[1]] = int(components[1])
    
    def _lwfFunc(self, attribute, data, op):
        """Lwf on/off based on Max GAMMALUT settings.
        """
        doc = documents.GetActiveDocument()
        
        if data.lower() == "true":
            doc[c4d.DOCUMENT_LINEARWORKFLOW] = 1
        else:
            doc[c4d.DOCUMENT_LINEARWORKFLOW] = 0

    #----------------------- Modifier Functions ----------------------------------
    
    def _angleToRad(self,attribute, data):
        return c4d.utils.Rad(data)
    
    def _divideBy(self, attribute, data):
        return data / attribute.modifierParam
            
    def _multiplyBy(self, attribute, data):
        return data * attribute.modifierParam
    
    def _invertPerc(self, attribute, data):
        return 1.0-float(data)
    
    def _maxGenericToCmFloat(self, attribute, data):
        return data * 2.54
    
    def _convertAreaLightSize(self, attribute, data):
        
        #Convert from half-width to width
        newdata = data*2
        
        if self._fileUnits=="inches":
            newdata *= 2.54
        elif self._fileUnits=="millimeters":
            newdata /= 10
        
        return newdata
        
    def _convertPhotometricIntensity(self, attribute, data):
        return data *10
    
    #----------------------- Convert Functions -----------------------------------
    
    def _vrayLightConvert(self, attribute, data):
        """ Take std desc if set in vrayLightStr array.
        """ 
        if self._vrayLightConvStr.has_key((attribute.name, str(data).lower())):
            stdStr = self._vrayLightConvStr[(attribute.name, str(data).lower())]
            if stdStr:
                if self._quickMode:
                    if str(attribute.name)== "v_shadow" and str(data)=="true":
                        return self._lightStr["shadow", "shadowmap"]
                    else:
                        return self._lightStr[stdStr]
                else:        
                    return self._lightStr[stdStr]

    def _vrayMaterialConvert(self, attribute, data):
        """ Take std desc if set in vrayMaterialStr array.
        """
        if self._vrayMaterialStr.has_key((attribute.name, str(data).lower())):
            stdStr = self._vrayMaterialStr[(attribute.name, str(data).lower())][1]
            if stdStr:
                return self._materialStr[self._vrayMaterialStr[(attribute.name, str(data).lower())][1]]
    
    #-----------------------------------------------------------------------------
    #-------------------------- Main Functions -----------------------------------
    #-----------------------------------------------------------------------------
    
    def _DecryptData(self, file):
        """Decrypt data based on the offset ENCRYPTION_OFFSET
        """
        data = ""
        line = file.readline()
        while line:
            line = line.strip('"\n\r')
            for i in xrange(len(line)):
                char = ord(line[i])
                data += chr((char + self.ENCRYPTION_OFFSET) % 127)
            data += "\n"
            line = file.readline()
        return data
        
    def _LoadFile(self):
        """Load xml file.
        """
        self._filePath = self.DIR_CURRENT+"/material.xml"
        if not os.path.exists(self._filePath):
            gui.MessageDialog("Could not find material file to import at "+self._filePath)
        file = open(self._filePath,'r')
        if self.ENCRYPTION:
            data = self._DecryptData(file)
        else:
            data = file.read()
        file.close()
        return data
        
    def _GetNodes(self, data, markup):
        """Get all <markup> markups.
        """
        nodes = []
        try:
            dom = parseString(data)            
            nodes = dom.getElementsByTagName(markup)
        except ExpatError as error:
            c4d.gui.MessageDialog(self._filePath + "\n\n" + str(error))
        return nodes
    
    def _GetFileUnits(self,data):
        nodes = self._GetNodes(data, "UnitsSystem")
        for node in nodes:
            if node.hasAttribute("name"):
                self._fileUnits = node.getAttribute("name")
        nodes = self._GetNodes(data, "metmultiplier")
        for node in nodes:
            if node.hasAttribute("name"):
                self._unitMultiplier = int(node.getAttribute("name"))
        nodes = self._GetNodes(data, "sysmultiplier")
        for node in nodes:
            if node.hasAttribute("name"):
                self._metricMultiplier = int(node.getAttribute("name"))
        nodes = self._GetNodes(data, "sversion")
        for node in nodes:
            if node.hasAttribute("name"):
                self._metricStandard = int(node.getAttribute("name"))
    
    def _cleanEmptyTexSlots(self, doc):
        """Return materials named 'name'.
        """
        materials = doc.GetMaterials()
        for mat in materials:
            shader = mat.GetFirstShader()
            if shader:
                self._ShaderSearch(shader, mat)
    
    def _ShaderSearch(self, shader, mat):
        next = shader.GetNext()
        down = shader.GetDown()
        try:
            self._ShaderSearch(shader.GetFirstShader(), mat)
        except AttributeError:
            pass
        if shader.GetName() == "Bitmap":
            if not "." in str(shader[c4d.BITMAPSHADER_FILENAME]):
                shader.Remove()
        if down:
            self._ShaderSearch(down, mat)
        if next:
            self._ShaderSearch(next, mat)
        
    def _GetNextHierarchyObject(self, op):
        """Return the next object in hieararchy.
        """
        if op is None:
            return None
        down = op.GetDown()
        if down:
            return down
        next = op.GetNext()
        if next:
            return next
        prev = op.GetUp()
        while prev:
            next = prev.GetNext()
            if next:
                return next
            prev = prev.GetUp()
        return None
        
    def _NullToLight(self, op):
        light = c4d.BaseObject(c4d.Olight)
        light.SetName(op.GetName())
        light.SetMl(op.GetMl())
        light.InsertBefore(op)
        op.Remove()
        op = light
        return op
    
    def _NullToCam(self, op):
        vcam = c4d.BaseObject(c4d.Ocamera)
        vcam.SetName(op.GetName())
        vcam.SetMg(op.GetMg())
        vcam.InsertBefore(op)
        op.Remove()
        op = vcam
        return op
    
    def _GetLights(self, name):
        """Return lights named 'name'.
        """
        found = []
        op = self._doc.GetFirstObject()
        while op:
            if op.GetName().lower() == name.lower():
                if op.GetType() == c4d.Onull:
                    op = self._NullToLight(op)
                if op.GetType() == c4d.Olight:
                    found.append(op)
            op = self._GetNextHierarchyObject(op)
        return found    
    
    def _GetStdLights(self):
        """Return std lights without vray tag.
        """
        found = []
        op = self._doc.GetFirstObject()
        while op:
            if op.GetType() == c4d.Olight:
                if self._vrayLights and not op.GetTag(1020441):
                    tag = c4d.BaseTag(self.VRAY_LIGHT_TAG)
                    op.InsertTag(tag)
                    op.Message(c4d.MSG_UPDATE)
                    ##tag[c4d.VRAYLIGHTTAG_COMMON_INTENSITY] = op[c4d.LIGHT_BRIGHTNESS]/10000000
                    op[c4d.LIGHT_BRIGHTNESS] /= 10000
                    c4d.DrawViews(c4d.DRAWFLAGS_ONLY_ACTIVE_VIEW|c4d.DRAWFLAGS_NO_THREAD|c4d.DRAWFLAGS_NO_REDUCTION|c4d.DRAWFLAGS_STATICBREAK)
            op = self._GetNextHierarchyObject(op)
        return found    
    
    def _ThrowError(self):
        c4d.gui.MessageDialog("A problem has occurred and the plugin must quit..")
        c4d.documents.KillDocument(c4d.documents.GetActiveDocument())
    
    def _GetVrayVideoPost(self, rd):
        """Returns the vray video post or create it.
        """
        if not c4d.GetCommandName(self.VRAY_CONVERTER):
          return None
        vp = rd.GetFirstVideoPost()
        while vp:
            if vp.GetType() == self.VRAYBRIDGE:
                return vp
            vp = vp.GetNext()
        vrayVideoPost = c4d.BaseList2D(self.VRAYBRIDGE)
        rd.InsertVideoPostLast(vrayVideoPost)
        return vrayVideoPost
    
    def _GetOctaneVideoPost(self, rd):
        """Returns the vray video post or create it.
        """
        #if not c4d.GetCommandName(self.VRAY_CONVERTER):
          #return None
        vp = rd.GetFirstVideoPost()
        while vp:
            if vp.GetType() == self.OCTANE:
                return vp
            vp = vp.GetNext()
        octaneVideoPost = c4d.BaseList2D(self.OCTANE)
        rd.InsertVideoPostLast(octaneVideoPost)
        return octaneVideoPost
        
    def _SetRenders(self, data):
        """Set the render attributes based on xml data.
        """
        self._initRenderArray()
        nodes = self._GetNodes(data, self.RENDER)
        for node in nodes:
            self._SetRenderTags(self._renderTags, node)
    
    def _SetRenderTags(self, attributesTab, node):
        """Set the xml render tags.
        """
        if not self._vrayMaterials and not self._usingOctane:
            tagNodes = node.getElementsByTagName("vray_GlobalIllumination")
            for tagNode in tagNodes:
                if tagNode.hasAttribute("enableGI"):
                    if tagNode.getAttribute("enableGI")=="true":
                        #Switch on GI
                        rd = self._doc.GetActiveRenderData()
                        videoPost = c4d.BaseList2D(1021096)
                        videoPost[c4d.GI_SETUP_DATA_PRIMARY_METHOD] = 6043
                        videoPost[c4d.GI_SETUP_DATA_SECONDARY_METHOD] = 6045
                        videoPost[c4d.GI_SETUP_DATA_IC2_QUALITY] = 6071
                        videoPost[c4d.GI_SETUP_DATA_QMC_COUNT_THRESHOLD] = 0.5
                        videoPost[c4d.GI_SETUP_DATA_IC2_SMOOTHING] = 1
                        videoPost[c4d.GI_SETUP_DATA_IC2_RATE_MIN] = -3
                        videoPost[c4d.GI_SETUP_DATA_IC2_RATE_MAX] = -1
                        videoPost[c4d.GI_SETUP_DATA_IC2_DENSITY] = 0.3
                        videoPost[c4d.GI_SETUP_DATA_IC2_DETAILS] = 0.8
                        videoPost[c4d.GI_SETUP_DATA_IC2_MAX_LIMIT] = 0.5
                        videoPost[c4d.GI_SETUP_DATA_RADIANCE_SCALE] = 0.5
                        videoPost[c4d.GI_SETUP_DATA_RADIANCE_AREA_ENABLE] = True
                        videoPost[c4d.GI_SETUP_DATA_RADIANCE_AREA_SAMPLES] = 32
                        videoPost[c4d.GI_SETUP_DATA_RADIANCE_SKY_ENABLE] = True
                        videoPost[c4d.GI_SETUP_DATA_RADIANCE_SKY_SAMPLES] = 32
                        rd.InsertVideoPostLast(videoPost)
        
        renderNode = node.firstChild
        while renderNode:
            if renderNode.nodeType==1:
                for attribute in attributesTab:
                    if renderNode.tagName == attribute[0]:
                        if renderNode.hasAttribute(attribute[1].name):
                            data = renderNode.getAttribute(attribute[1].name)
                            #Set the usual RenderPost parameters the normal way
                            if attribute[1].setFunction != None:
                                self._SetRenderTag(attribute[1], data)
                shaderNodes = renderNode.getElementsByTagName("shader")
                #Set all RenderPost shaders here
                for shaderNode in shaderNodes:
                    for shaderDestAttr in self._materialAttributes:
                        if shaderNode.getAttribute("Name").lower()==shaderDestAttr.name.lower():
                            vray=False
                            for shaderType in self._shaderTypes:
                                if shaderNode.getAttribute("Type").lower()==shaderType.name.lower():
                                    shaderTypeInt = shaderType.desc
                                    if shaderType.vrayAttribute:
                                        vray=True
                                    rd = self._doc.GetActiveRenderData()
                                    if vray:
                                        vp = self._GetVrayVideoPost(rd)
                                        shader = self._utilityShaderFunc(shaderDestAttr.desc,shaderTypeInt,vp,vray)
                                        bc = shader.GetDataInstance()
                                        shaderAttributes = self._vrayShaderAttributes
                                        for shaderAttr in shaderAttributes:
                                            if shaderNode.hasAttribute(shaderAttr.shaderName):
                                                if not shaderNode.hasAttribute(shaderAttr.shaderName):
                                                    self._ThrowError()
                                                data = shaderNode.getAttribute(shaderAttr.shaderName)
                                                if (shaderAttr.shaderName=="Path"):
                                                    shaderAttr.setFunction(shaderAttr, data, shader)
                                                else:
                                                    shaderAttr.setFunction(shaderAttr, data, shader)
                                                shader.Message(c4d.MSG_UPDATE)
                                        subNode = shaderNode.firstChild
                                        while subNode:
                                            if subNode.nodeType==1:
                                                if subNode.hasAttribute("paramName"):
                                                    if subNode.getAttribute("paramName") == "Output":
                                                        if subNode.hasAttribute("output_rgb_level"):
                                                            rgbLevel = float(subNode.getAttribute("output_rgb_level"))
                                                            if shaderNode.getAttribute("Name")=="giMapShader":
                                                                vp[c4d.VP_VRAYBRIDGE_ENVIRONMENT_GIMAPMUL] = rgbLevel
                                                            elif shaderNode.getAttribute("Name")=="rrMapShader":
                                                                vp[c4d.VP_VRAYBRIDGE_ENVIRONMENT_REFLMAPMUL] = rgbLevel
                                            subNode = subNode.nextSibling
                                    else:
                                        if attribute[0] == "vray_Environment":
                                            #CREATE LUMINANCE MATERIAL TO HOLD VRAY ENVIRONMENT MAPS
                                            skyObj = self._doc.SearchObject("Sky")
                                            if skyObj and skyObj.GetType()==5105 and skyObj.GetFirstTag()==None:
                                                mat = c4d.BaseMaterial(c4d.Mmaterial)
                                                mat[c4d.MATERIAL_USE_LUMINANCE] = True
                                                bitmap = c4d.BaseShader(c4d.Xbitmap)
                                                bitmap[c4d.BITMAPSHADER_FILENAME]=str(shaderNode.getAttribute("Path"))
                                                mat.InsertShader(bitmap)
                                                mat[c4d.MATERIAL_LUMINANCE_SHADER] = bitmap
                                                mat[c4d.MATERIAL_USE_COLOR] = False
                                                mat[c4d.MATERIAL_USE_SPECULAR] = False
                                                mat.SetName("Environment")
                                                mat.Message(c4d.MSG_UPDATE)
                                                mat.Update(True, True)
                                                self._doc.InsertMaterial(mat)
                                                tag = c4d.BaseTag(c4d.Ttexture)
                                                tag.SetMaterial(mat)
                                                skyObj.InsertTag(tag)
            renderNode = renderNode.nextSibling
    
    def _SetRenderTag(self, attribute, data):
        """Set the xml render tag.
        """
        rd = self._doc.GetActiveRenderData()
        if attribute.vrayAttribute and (c4d.GetCommandName(self.VRAY_CONVERTER) != ""):
            vp = self._GetVrayVideoPost(rd)
            bc = vp.GetData()
            attribute.setFunction(attribute, data, bc)
            vp.SetData(bc)
            vp.Message(c4d.MSG_UPDATE)
        else:
            attribute.setFunction(attribute, data, rd)
            rd.Message(c4d.MSG_UPDATE)
    
    def _SetDisplacementMaterials(self, data):
        """Set the blend materials attributes based on xml data.
        """
        nodes = self._GetNodes(data, "displacementmodifier")
        for node in nodes:
            self._SetDisplacementMaterial(node, data)
    
    def _SetDisplacementMaterial(self, node, data):
        """Set the material attributes based on xml data.
        """ 
        if node.hasAttribute(self.NAME):  
            if self._vrayMaterials:
                ###############################################
                ##### VRay Max Displacement Modifier ##########
                ###############################################
                
                #Create and insert VRayDisplacement material
                mat = c4d.BaseMaterial(1022593)
                mat.SetName("VR_DISPL"+str(node.getAttribute(self.NAME)))
                self._doc.InsertMaterial(mat)
                
                self._SetMaterialAttributes(self._materialAttributes, node, mat)
                self._SetShaders(node, mat)
                
                tag = c4d.BaseTag(c4d.Ttexture)
                tag.SetMaterial(mat)
                tag[c4d.TEXTURETAG_PROJECTION] = 6
                
                obj = self._doc.SearchObject(node.getAttribute("displacementmod_Object"))
                appliedToParentSubdivObject = False
                geomNodes = self._GetNodes(data, "geometry")
                for geomNode in geomNodes:
                    if geomNode.hasAttribute("name"):
                        objName = geomNode.getAttribute("name")
                        if (objName==node.getAttribute("displacementmod_Object")):
                            if geomNode.hasAttribute("turbosmooth"):
                                if (int(geomNode.getAttribute("turbosmooth"))>0):
                                    objParent = obj.GetUp()
                                    if (objParent.GetTypeName()=="Subdivision Surface"):
                                        appliedToParentSubdivObject = True
                                        objParent.InsertTag(tag)
                if (appliedToParentSubdivObject==False):
                    if (obj is not None):
                        obj.InsertTag(tag)
                
                mat.Message(c4d.MSG_UPDATE)
                mat.Update(True, True)
                
            else:
                #####################################################
                ### VRay Max Displacement Modifier -> STANDARD C4D ##
                #####################################################
                
                #For standard c4d..
                print "Create Std Displacement"  
    
    def _SetCarPaintMaterials(self, data):
        """Set the blend materials attributes based on xml data.
        """
        nodes = self._GetNodes(data, "carpaintmaterial")
        for node in nodes:
            self._SetCarPaintMaterial(node)
    
    def _SetCarPaintMaterial(self, node):
        """Set the material attributes based on xml data.
        """ 
        if node.hasAttribute(self.NAME):  
            if self._vrayMaterials:
                ###############################################
                ##### VRay Max CarPaintMaterial ###############
                ###############################################
                
                #Create and insert VRayOverride material
                mat = c4d.BaseMaterial(1029457)
                mat.SetName("VR_CARPAINT"+str(node.getAttribute(self.NAME)))
                self._doc.InsertMaterial(mat)
                
                self._SetMaterialAttributes(self._materialAttributes, node, mat)
                self._SetShaders(node, mat)
                #Search all scene object texture tags for tag with same name as 2sided mat, then replace with new mat reference
                #This is because the scene imports with some random mat instead of 2sided, but tag is named after correct mat
                op = self._doc.GetFirstObject()
                while op:
                    tags = op.GetTags()
                    for tag in tags:
                        if tag.GetType()==c4d.Ttexture:
                            if tag.GetName() == node.getAttribute(self.NAME):
                                if tag.GetMaterial().GetName() != mat.GetName():
                                    tag.SetMaterial(mat)
                                    self._tagMatsDoNotReplace.append(mat.GetName())
                    op = self.GetNextHierarchyObject(op)
                
                mat.Message(c4d.MSG_UPDATE)
                mat.Update(True, True)
                
            else:
                #####################################################
                ##### VRay Max CarPaintMaterial -> STANDARD C4D #####
                #####################################################
                
                #For standard c4d..
                mat = c4d.BaseMaterial(c4d.Mmaterial)
                mat.SetName(str(node.getAttribute(self.NAME)))
                
                self._doc.InsertMaterial(mat)
                
                op = self._doc.GetFirstObject()
                while op:
                    tags = op.GetTags()
                    for tag in tags:
                        if tag.GetType()==c4d.Ttexture:
                            if tag.GetName() == node.getAttribute(self.NAME):
                                tag.SetMaterial(mat)
                                self._tagMatsDoNotReplace.append(mat.GetName())
                    op = self.GetNextHierarchyObject(op)
    
    def _SetLightMaterials(self, data):
        """Set the Light materials attributes based on xml data.
        """
        nodes = self._GetNodes(data, self.LIGHTMATERIAL)
        for node in nodes:
            self._SetLightMaterial(node)
    
    def _SetLightMaterial(self, node):
        """Set the material attributes based on xml data.
        """ 
        if node.hasAttribute(self.NAME):  
            if self._vrayMaterials:
                mat = c4d.BaseMaterial(1020295)
                mat.SetName("VR_LIGHT"+str(node.getAttribute(self.NAME)))
                self._doc.InsertMaterial(mat)
                
                self._SetMaterialAttributes(self._materialAttributes, node, mat)
                self._SetShaders(node, mat)
                
                mat[c4d.VRAYMATERIAL_LUMINANCE_TRANSP_MULT] = 0
                mat[c4d.VRAYMATERIAL_USE_COLOR1] = False
                mat[c4d.VRAYMATERIAL_USE_SPECULAR1] = False
            elif self._usingOctane:
                mat = c4d.BaseMaterial(1029501)
                mat.SetName("OCT_LIGHT_"+str(node.getAttribute(self.NAME)))
                
                blackbodyShader = c4d.BaseShader(1029641)
                mat.InsertShader(blackbodyShader)
                mat[c4d.OCT_MATERIAL_EMISSION] = blackbodyShader
                
                self._doc.InsertMaterial(mat)
                
                self._SetMaterialAttributes(self._materialAttributes, node, mat)
                self._SetShaders(node, mat)
            else:
                mat = c4d.BaseMaterial(c4d.Mmaterial)
                mat.SetName(str(node.getAttribute(self.NAME)))
                self._doc.InsertMaterial(mat)
                
                self._SetMaterialAttributes(self._materialAttributes, node, mat)
                self._SetShaders(node, mat)
                
                mat[c4d.MATERIAL_USE_COLOR] = False
                mat[c4d.MATERIAL_USE_SPECULAR] = False
            
            #Search all scene object texture tags for tag with same name as Light mat, then replace with new mat reference
            #This is because the scene imports with some random mat instead of Light, but tag is named after correct mat
            op = self._doc.GetFirstObject()
            while op:
                tags = op.GetTags()
                for tag in tags:
                    if tag.GetType()==c4d.Ttexture:
                        if tag.GetName() == node.getAttribute(self.NAME):
                            if tag.GetMaterial().GetName() != mat.GetName():
                                tag.SetMaterial(mat)
                                self._tagMatsDoNotReplace.append(mat.GetName())
                op = self.GetNextHierarchyObject(op)
            
            mat.Message(c4d.MSG_UPDATE)
            mat.Update(True, True)
        
    def _SetOverrideMaterials(self, data):
        """Set the Override materials attributes based on xml data.
        """
        nodes = self._GetNodes(data, self.OVERRIDEMATERIAL)
        for node in nodes:
            self._SetOverrideMaterial(node)
    
    def _SetOverrideMaterial(self, node):
        """Set the material attributes based on xml data.
        """ 
        if node.hasAttribute(self.NAME):  
            if self._vrayMaterials:
                ###############################################
                ##### VRay Max OverrideMaterial ###############
                ###############################################
                
                #Create and insert VRayOverride material
                mat = c4d.BaseMaterial(1023126)
                mat.SetName("VR_OVERRIDE"+str(node.getAttribute(self.NAME)))
                self._doc.InsertMaterial(mat)
                
                self._SetMaterialAttributes(self._materialAttributes, node, mat)
                
                #Search all scene object texture tags for tag with same name as 2sided mat, then replace with new mat reference
                #This is because the scene imports with some random mat instead of 2sided, but tag is named after correct mat
                op = self._doc.GetFirstObject()
                while op:
                    tags = op.GetTags()
                    for tag in tags:
                        if tag.GetType()==c4d.Ttexture:
                            if tag.GetName() == node.getAttribute(self.NAME):
                                if tag.GetMaterial().GetName() != mat.GetName():
                                    tag.SetMaterial(mat)
                                    self._tagMatsDoNotReplace.append(mat.GetName())
                    op = self.GetNextHierarchyObject(op)
                
                mat.Message(c4d.MSG_UPDATE)
                mat.Update(True, True)
                
            else:
                #####################################################
                ##### VRay Max OverrideMaterial -> STANDARD C4D #####
                #####################################################
                
                #For standard c4d, just assign Base material to object instead..
                op = self._doc.GetFirstObject()
                while op:
                    tags = op.GetTags()
                    for tag in tags:
                        if tag.GetType()==c4d.Ttexture:
                            if tag.GetName() == node.getAttribute(self.NAME):
                                mats = self._GetMaterials(node.getAttribute("baseMaterial"))
                                if len(mats) != 0:
                                    tag.SetMaterial(mats[0])
                                    self._tagMatsDoNotReplace.append(mats[0].GetName())
                    op = self.GetNextHierarchyObject(op)
                    
    def _SetTwoSidedMaterials(self, data):
        """Set the blend materials attributes based on xml data.
        """
        nodes = self._GetNodes(data, self.TWOSIDEDMATERIAL)
        for node in nodes:
            self._SetTwoSidedMaterial(node)
    
    def _SetTwoSidedMaterial(self, node):
        """Set the material attributes based on xml data.
        """ 
        if node.hasAttribute(self.NAME):  
            if self._vrayMaterials:
                ###############################################
                ##### VRay Max TwoSidedMaterial ###############
                ###############################################
                
                #Create and insert VRayTwoSided material
                mat = c4d.BaseMaterial(1022115)
                mat.SetName("VR_TWOSIDED"+str(node.getAttribute(self.NAME)))
                self._doc.InsertMaterial(mat)
                
                self._SetMaterialAttributes(self._materialAttributes, node, mat)
                
                #Assign Front material to Back material if backmat doesn't exist ( its what max does )
                if node.getAttribute("backMtlOn") == "false":
                    mat[c4d.VRAY2SIDEDMATERIAL_PARAMS_LINK2] = mat[c4d.VRAY2SIDEDMATERIAL_PARAMS_LINK1]
                
                #Search all scene object texture tags for tag with same name as 2sided mat, then replace with new mat reference
                #This is because the scene imports with some random mat instead of 2sided, but tag is named after correct mat
                op = self._doc.GetFirstObject()
                while op:
                    tags = op.GetTags()
                    for tag in tags:
                        if tag.GetType()==c4d.Ttexture:
                            if tag.GetName() == node.getAttribute(self.NAME):
                                if tag.GetMaterial().GetName() != mat.GetName():
                                    tag.SetMaterial(mat)
                                    self._tagMatsDoNotReplace.append(mat.GetName())
                    op = self.GetNextHierarchyObject(op)
                
                mat.Message(c4d.MSG_UPDATE)
                mat.Update(True, True)
                
            else:
                #####################################################
                ##### VRay Max TwoSidedMaterial -> STANDARD C4D #####
                #####################################################
                
                data = node.getAttribute("frontMaterial")
                if ":" in data:
                    data = str(data[0:data.index(":")])
                mats = self._GetMaterials(data)
                if len(mats) != 0:
                    frontMat = mats[0]
                    frontMatName = frontMat.GetName()
                    frontMat[c4d.MATERIAL_USE_TRANSPARENCY] = True
                    components = node.getAttribute("translucency").split()
                    color = c4d.Vector(int(components[0]), int(components[1]), int(components[2])) / 255.0
                    frontMat[c4d.MATERIAL_TRANSPARENCY_COLOR] = color
                    frontMat[c4d.MATERIAL_TRANSPARENCY_BRIGHTNESS] = 1
                    frontMat[c4d.MATERIAL_TRANSPARENCY_REFRACTION] = 1
                
                if node.getAttribute("backMtlOn")=="true":
                    data = node.getAttribute("backMaterial")
                    if ":" in data:
                        data = str(data[0:data.index(":")])
                    mats = self._GetMaterials(data)
                    if len(mats) != 0:
                        backMat = mats[0]
                        backMatName = backMat.GetName()
                        backMat[c4d.MATERIAL_USE_TRANSPARENCY] = True
                        backMat[c4d.MATERIAL_TRANSPARENCY_COLOR] = color
                        backMat[c4d.MATERIAL_TRANSPARENCY_BRIGHTNESS] = 1
                        backMat[c4d.MATERIAL_TRANSPARENCY_REFRACTION] = 1
                
                op = self._doc.GetFirstObject()
                while op:
                    tags = op.GetTags()
                    for tag in tags:
                        if tag.GetType()==c4d.Ttexture:
                            if tag.GetName() == node.getAttribute(self.NAME):
                                if tag.GetMaterial().GetName() != frontMatName:
                                    tag.SetMaterial(frontMat)
                                    if node.getAttribute("backMtlOn")=="true":
                                        tag[c4d.TEXTURETAG_SIDE] = 1 #Set texture tag SIDE to FRONT
                                        self._tagMatsDoNotReplace.append(frontMatName)
                                        backTag = c4d.BaseTag(c4d.Ttexture)
                                        backTag.SetData(tag.GetData())
                                        backTag.SetName(backMatName)
                                        backTag.SetMaterial(backMat)
                                        backTag[c4d.TEXTURETAG_SIDE] = 2 #Set texture tag SIDE to BACK
                    op = self.GetNextHierarchyObject(op)
    
    def _SetFastSSS2Materials(self, data):
        """Set the blend materials attributes based on xml data.
        """
        nodes = self._GetNodes(data, self.FASTSSS2MATERIAL)
        for node in nodes:
            self._SetFastSSS2Material(node)
    
    def _SetFastSSS2Material(self, node):
        """Set the material attributes based on xml data.
        """ 
        if node.hasAttribute(self.NAME):
            if self._vrayMaterials:
                ###############################################
                ##### VRay Max FastSSS2Material ###############
                ###############################################
                
                #Create and insert VRayFastSSS2Material material
                mat = c4d.BaseMaterial(1024192)
                mat.SetName("VR_FASTSSS2"+str(node.getAttribute(self.NAME)))
                self._doc.InsertMaterial(mat)
                
                self._SetMaterialAttributes(self._materialAttributes, node, mat)
                self._SetShaders(node, mat)
                
                #Search all scene object texture tags for tag with same name as 2sided mat and replace with new mat reference
                op = self._doc.GetFirstObject()
                while op:
                    tags = op.GetTags()
                    for tag in tags:
                        if tag.GetType()==c4d.Ttexture:
                            if tag.GetName() == node.getAttribute(self.NAME):
                                if tag.GetMaterial().GetName() != mat.GetName():
                                    tag.SetMaterial(mat)
                                    self._tagMatsDoNotReplace.append(mat.GetName())
                    op = self.GetNextHierarchyObject(op)
                
                mat.Message(c4d.MSG_UPDATE)
                mat.Update(True, True)
                
            else:
                ######################################################################################
                ##### VRay Max FastSSS2Material -> STANDARD C4D with SubsurfaceScattering Shader #####
                ######################################################################################
                
                #Find the Standard material
                mats = self._GetMaterialsUtil(str(node.getAttribute(self.NAME)))
                mat = mats[0]
                
                self._SetMaterialAttributes(self._materialAttributes, node, mat)
                self._SetShaders(node, mat)
    
    def _SetBlendMaterials(self, data):
        """Set the blend materials attributes based on xml data.
        """
        nodes = self._GetNodes(data, self.BLENDMATERIAL)
        for node in nodes:
            self._SetBlendMaterial(node, nodes, data, False)
    
    def _SetBlendMaterial(self, node, allnodes, data, recursive=False,parentMat=None,subBlend=False,alreadyCreated=False,parentNode=None,parentSlot=0):
        """Set the material attributes based on xml data.
        """ 
        # print "=================================="
        createMat = True
        thisMatName = node.getAttribute(self.NAME)
        # if subBlend:
            # print "BLENDMAT(submat) = "+thisMatName
        # else:
            # print "BLENDMAT = "+thisMatName
        for i in xrange(len(self.createdBlendMatList)):
            if self.createdBlendMatList[i] == thisMatName:
                createMat = False
        
        if subBlend and alreadyCreated:
            print "New Blend Function"
            #self._getMaterials(thisMatName)
            parentName = parentNode.getAttribute("name")
            for node in allnodes:
                if (node.getAttribute(self.NAME)==parentName):
                    vray = False
                    if node.hasAttribute(self.VRAY):
                        if node.getAttribute(self.VRAY).lower() == "true":
                            vray = True
                    submats = []
                    submats.append(["base_material","material1"])
                    submats.append(["coatMaterial0","material2"])
                    submats.append(["coatMaterial1"])
                    submats.append(["coatMaterial2"])
                    submats.append(["coatMaterial3"])
                    if vray:
                        amountToCheck = 5 #Max VrayBlend has up to 5 mats
                        toggle = 0
                    else:
                        amountToCheck = 2 #Max StdBlend has only 2 mats
                        toggle = 1
            
        
        elif node.hasAttribute(self.NAME) and createMat:
            
            # print "Creating Blend Mat - "+node.getAttribute(self.NAME)
            self.createdBlendMatList.append(node.getAttribute(self.NAME)) ##Add this BlendMat to the list of created BlendMats##
            
            #For each Submat slot in the XML, check if it refers to a Blend mat, and if it doesn't exist yet create it..
            vray = False
            if node.hasAttribute(self.VRAY):
                if node.getAttribute(self.VRAY).lower() == "true":
                    vray = True
            submats = []
            submats.append(["base_material","material1"])
            submats.append(["coatMaterial0","material2"])
            submats.append(["coatMaterial1"])
            submats.append(["coatMaterial2"])
            submats.append(["coatMaterial3"])
            if vray:
                amountToCheck = 5 #Max VrayBlend has up to 5 mats
                toggle = 0
            else:
                amountToCheck = 2 #Max StdBlend has only 2 mats
                toggle = 1
            for i in xrange(amountToCheck):
                #If the Material Slot exists in XML , check if it is in the XML BlendMat list..
                if node.hasAttribute(submats[i][toggle]):
                    slotMat = node.getAttribute(submats[i][toggle])
                    baseBlendMatNode = ""
                    for blendNode in allnodes:  ##Allnodes is the BlendMat list, passed from parent function##
                        if blendNode.getAttribute('name') == slotMat:
                            baseBlendMatNode = blendNode
                    if baseBlendMatNode != "":
                        #If the XML BlendMats contains a reference to that mat, check if it has already been created..
                        createMat = True
                        for i in xrange(len(self.createdBlendMatList)):
                            if self.createdBlendMatList[i] == slotMat:
                                self._GetMaterialsUtil("VR_BLEND"+self.createdBlendMatList[i])[0].Remove()
                                createMat = False
                        if createMat:
                            # print "Submat is Blend - Firing _SetBlendMaterial = "+baseBlendMatNode.getAttribute("name")
                            #If it doesn't exist, create it..
                            self._SetBlendMaterial(baseBlendMatNode,allnodes,data,subBlend=True) ##Pass the SUBMAT param to the function##
                        else:
                            subBlend=True
                            # print "Submat is Blend - But already created = "+baseBlendMatNode.getAttribute("name")
                            self._SetBlendMaterial(baseBlendMatNode,allnodes,data,subBlend=True,alreadyCreated=True,parentNode=node) ##Pass the SUBMAT param to the function##
                            
            if self._vrayMaterials and not subBlend:
                
                ###############################################
                ##### Std and VRay Max Blend ##################
                ###############################################
                
                #Create and insert VRayBlend material
                mat = c4d.BaseMaterial(1022116)
                mat.SetName("VR_BLEND"+str(node.getAttribute(self.NAME)))
                self._doc.InsertMaterial(mat)
                
                # print "Inserting - "+ mat.GetName()
                
                ##HAVE TO CHECK IF ITS SEARCHING FOR "VR_BLEND" WHEN IT ATTEMPTS TO ASSIGN SUBMATS HERE...##
                self._SetMaterialAttributes(self._materialAttributes, node, mat)
                #Build list of coat mats and their associated weight/blendamount param
                tempObj = c4d.BaseObject(c4d.Ocube)
                self._doc.InsertObject(tempObj)
                self._tempObjects.append(tempObj)
                
                if mat[c4d.VRAYBLENDMATERIAL_PARAMS_LINK10] is not None:
                    
                    tempTag = c4d.BaseTag(c4d.Ttexture)
                    tempTag.SetMaterial(mat[c4d.VRAYBLENDMATERIAL_PARAMS_LINK10])
                    tempObj.InsertTag(tempTag)
                    
                    if mat[c4d.VRAYBLENDMATERIAL_PARAMS_LINK10][self.VRAY_WEIGHT_SHADER] is None:
                        mat[c4d.VRAYBLENDMATERIAL_PARAMS_LINK10][self.VRAY_USE_REFRACTION] = False
                
                coatMats = []
                coatMats.append([mat[c4d.VRAYBLENDMATERIAL_PARAMS_LINK9],"coatShader0", "texturemap_blend_mult0", "color_blend0", "amount1"])
                coatMats.append([mat[c4d.VRAYBLENDMATERIAL_PARAMS_LINK8],"coatShader1", "texturemap_blend_mult1", "color_blend1", "amount2"])
                coatMats.append([mat[c4d.VRAYBLENDMATERIAL_PARAMS_LINK7],"coatShader2", "texturemap_blend_mult2", "color_blend2", "amount3"])
                coatMats.append([mat[c4d.VRAYBLENDMATERIAL_PARAMS_LINK6],"coatShader3", "texturemap_blend_mult3", "color_blend3", "amount4"])
                
                for coatMat in coatMats:
                    if coatMat[0]:
                        print "Doing Coat - "+str(coatMat[0].GetName())
                        tempTag = c4d.BaseTag(c4d.Ttexture)
                        tempTag.SetMaterial(coatMat[0])
                        tempObj.InsertTag(tempTag)
                        #Set the weight shader for each coat mat to the weight/blendamount param
                        #If its VRayBlend mat then use these shader_blend params, otherwise just use the 'mask' param from std max blend.
                        if vray:
                            #Setting vray blend shader to set color value base and shader to mix for total coat blend amount
                            # print "     Creating Blend.."
                            blendShader = c4d.BaseShader(1011109)
                            coatMat[0][self.VRAY_WEIGHT_SHADER] = blendShader
                            colorShader = c4d.BaseShader(5832)
                            blendShader.InsertShader(colorShader)
                            self._colorFunc(XmlMaterialAttribute(None, c4d.COLORSHADER_COLOR, None, None), node.getAttribute(coatMat[3]), colorShader)   #COLOR A COLOR        #Set first blend channel as color
                            blendShader[c4d.SLA_FUSION_BASE_CHANNEL] = colorShader
                            # print "     coat_shader = "+coatMat[1]
                            #shaderNode.parentNode
                            self._SetShaders(node, blendShader, coatMat[1])                                                                 #Set second blend channel as shader
                            if (blendShader[c4d.SLA_FUSION_BLEND_CHANNEL] == None): #COLOR B TEX
                                #If no blend shader/map - set mix to zero and just use color value for blend amount
                                blendShader[c4d.SLA_FUSION_BLEND] = 0 #BLEND AMOUNT
                            else:
                                blendShader[c4d.SLA_FUSION_BLEND] = float(node.getAttribute(coatMat[2]))/100  #BLEND AMOUNT                                          #Set blend amount based on XML
                            coatMat[0].InsertShader(blendShader)
                            coatMat[0][self.VRAY_USE_REFRACTION] = 1
                            coatMat[0][self.VRAY_WEIGHT_TEXINVERT] = 1
                            ########################################
                            # blendShader = c4d.BaseList2D(self.VRAYSHADER)
                            # blendShader[c4d.VRAY_SHADERS_LIST] = 50
                            # coatMat[0][self.VRAY_WEIGHT_SHADER] = blendShader
                            # if not node.hasAttribute(coatMat[3]):
                                # if node.hasAttribute(coatMat[4]):
                                    # colorval = str((int((float(node.getAttribute(coatMat[4]))/100.0)*255)))
                                    # color = str(colorval+" "+colorval+" "+colorval)
                                    # self._colorFunc(XmlMaterialAttribute(None, 92831086, None, None), color, blendShader)   #Set first blend channel as color
                            # else:
                                # self._colorFunc(XmlMaterialAttribute(None, 92831086, None, None), node.getAttribute(coatMat[3]), blendShader)   #Set first blend channel as color
                            # self._SetShaders(node, blendShader, coatMat[1])                                                                 #Set second blend channel as shader
                            # if (blendShader[92984986] == None):
                                #If no blend shader/map - set mix to zero and just use color value for blend amount
                                # blendShader[92831088] = 0
                            # else:
                                # blendShader[92831088] = float(node.getAttribute(coatMat[2]))/100                                            #Set blend amount based on XML
                            # coatMat[0].InsertShader(blendShader)
                            # blendShader[92984886] = None                                                                                    #Clear first blend channel shader slot
                        else:
                            if node.hasAttribute("shellacColorBlend"):
                                #Shellac Material emulated as Std Blend
                                colorShader = c4d.BaseShader(5832)
                                color = float(node.getAttribute("shellacColorBlend"))
                                colorval = float((int((color/100.0)*255)))
                                colorShader[c4d.COLORSHADER_COLOR] = c4d.Vector(colorval,colorval,colorval)/255 # Create greyscale color from blend amount
                                coatMat[0].InsertShader(colorShader)
                                coatMat[0][self.VRAY_WEIGHT_SHADER] = colorShader
                            else:
                                self._SetShaders(node, coatMat[0], nodeName='mask')
                        coatMat[0][self.VRAY_USE_REFRACTION] = 1
                        coatMat[0][self.VRAY_WEIGHT_TEXINVERT] = 1
                        # print "     DONE."
                mat.Message(c4d.MSG_UPDATE)
                mat.Update(True, True)
            elif not self._vrayMaterials or subBlend:
                # print "subBlend = "+str(subBlend)
                if vray:
                    # print "VRAY Subblend = True"
                    ###############################################
                    ##### VRAY Max Blend ##########################
                    ###############################################
                    
                    #Build list of coat mats and their associated weight/blendamount param
                    coatMats = []
                    coatMat = self._GetMaterials(node.getAttribute("coatMaterial0"))
                    if len(coatMat)!=0:
                        coatMats.append([coatMat[0],"coatShader0", "texturemap_blend_mult0", "color_blend0", "amount1"])
                    coatMat = self._GetMaterials(node.getAttribute("coatMaterial1"))
                    if len(coatMat)!=0:
                        coatMats.append([coatMat[0],"coatShader1", "texturemap_blend_mult1", "color_blend1", "amount2"])
                    coatMat = self._GetMaterials(node.getAttribute("coatMaterial2"))
                    if len(coatMat)!=0:
                        coatMats.append([coatMat[0],"coatShader2", "texturemap_blend_mult2", "color_blend2", "amount3"])
                    coatMat = self._GetMaterials(node.getAttribute("coatMaterial3"))
                    if len(coatMat)!=0:
                        coatMats.append([coatMat[0],"coatShader3", "texturemap_blend_mult3", "color_blend3", "amount4"])
                    
                    for coatMat in coatMats:
                        if coatMat[0]:
                            #Set the weight shader for each coat mat to the weight/blendamount param
                            #Use these shader_blend params.
                            #Setting vray blend shader to set color value base and shader to mix for total coat blend amount
                            if self._vrayMaterials:
                                blendShader = c4d.BaseShader(1011109)
                                coatMat[0][self.VRAY_WEIGHT_SHADER] = blendShader
                                colorShader = c4d.BaseShader(5832)
                                blendShader.InsertShader(colorShader)
                                self._colorFunc(XmlMaterialAttribute(None, c4d.COLORSHADER_COLOR, None, None), node.getAttribute(coatMat[3]), colorShader)   #COLOR A COLOR        #Set first blend channel as color
                                blendShader[c4d.SLA_FUSION_BASE_CHANNEL] = colorShader
                                self._SetShaders(node, blendShader, coatMat[1])                                                                 #Set second blend channel as shader
                                if (blendShader[c4d.SLA_FUSION_BLEND_CHANNEL] == None): #COLOR B TEX
                                    #If no blend shader/map - set mix to zero and just use color value for blend amount
                                    blendShader[c4d.SLA_FUSION_BLEND] = 0 #BLEND AMOUNT
                                else:
                                    blendShader[c4d.SLA_FUSION_BLEND] = float(node.getAttribute(coatMat[2]))/100  #BLEND AMOUNT                                          #Set blend amount based on XML
                                coatMat[0].InsertShader(blendShader)
                                coatMat[0][self.VRAY_USE_REFRACTION] = 1
                                coatMat[0][self.VRAY_WEIGHT_TEXINVERT] = 1
                                # blendShader[92984886] = None                                                                                    #Clear first blend channel shader slot
                            else:
                                blendShader = c4d.BaseShader(1011109)
                                coatMat[0][c4d.MATERIAL_ALPHA_SHADER] = blendShader
                                coatMat[0][c4d.MATERIAL_USE_ALPHA] = 1
                                coatMat[0][c4d.MATERIAL_ALPHA_INVERT] = 0
                                colorShader = c4d.BaseShader(5832)
                                blendShader.InsertShader(colorShader)
                                self._colorFunc(XmlMaterialAttribute(None, c4d.COLORSHADER_COLOR, None, None), node.getAttribute(coatMat[3]), colorShader)   #COLOR A COLOR        #Set first blend channel as color
                                blendShader[c4d.SLA_FUSION_BASE_CHANNEL] = colorShader
                                self._SetShaders(node, blendShader, coatMat[1])                                                                 #Set second blend channel as shader
                                if (blendShader[c4d.SLA_FUSION_BLEND_CHANNEL] == None): #COLOR B TEX
                                    #If no blend shader/map - set mix to zero and just use color value for blend amount
                                    blendShader[c4d.SLA_FUSION_BLEND] = 0 #BLEND AMOUNT
                                else:
                                    blendShader[c4d.SLA_FUSION_BLEND] = float(node.getAttribute(coatMat[2]))/100  #BLEND AMOUNT                                          #Set blend amount based on XML
                                coatMat[0].InsertShader(blendShader)
                                #blendShader[92984886] = None #COLOR A TEX                                                                                   #Clear first blend channel shader slot
                else:
                    #print "STD Subblend = True"
                    ###############################################
                    ##### Std Max Blend ###########################
                    ###############################################
                    if self._vrayMaterials:
                        secondMat = self._GetMaterials(node.getAttribute("material2"))
                        if len(secondMat)!=0:
                            if node.hasAttribute("shellacColorBlend"):
                                #Shellac Material emulated as Std Blend
                                colorShader = c4d.BaseShader(5832)
                                color = float(node.getAttribute("shellacColorBlend"))
                                colorval = float((int((color/100.0)*255)))
                                colorShader[c4d.COLORSHADER_COLOR] = c4d.Vector(colorval,colorval,colorval)/255 # Create greyscale color from blend amount
                                secondMat[0].InsertShader(colorShader)
                                secondMat[0][self.VRAY_WEIGHT_SHADER] = colorShader
                            else:
                                self._SetShaders(node, secondMat[0], nodeName='mask')
                            secondMat[0][self.VRAY_USE_REFRACTION] = 1
                            secondMat[0][self.VRAY_WEIGHT_TEXINVERT] = 1
                    else:
                        secondMat = self._GetMaterials(node.getAttribute("material2"))
                        if len(secondMat)!=0:
                            if node.hasAttribute("shellacColorBlend"):
                                #Shellac Material emulated as Std Blend
                                colorShader = c4d.BaseShader(5832)
                                color = float(node.getAttribute("shellacColorBlend"))
                                colorval = float((int((color/100.0)*255)))
                                colorShader[c4d.COLORSHADER_COLOR] = c4d.Vector(colorval,colorval,colorval)/255 # Create greyscale color from blend amount
                                secondMat[0].InsertShader(colorShader)
                                secondMat[0][c4d.MATERIAL_ALPHA_SHADER] = colorShader
                            else:
                                self._SetShaders(node, secondMat[0], nodeName='mask')
                                
                            secondMat[0][c4d.MATERIAL_USE_ALPHA] = 1
                            secondMat[0][c4d.MATERIAL_ALPHA_INVERT] = 0
    
    def _searchAndReplaceMat(self, oldMatName, newMat):
        op = self._doc.GetFirstObject()
        found = []
        while op:
            tags = op.GetTags()
            for tag in tags:
                if tag.GetType()==c4d.Ttexture:
                    if tag.GetMaterial().GetName()==oldMatName:
                        tag.SetMaterial(newMat)
                        found.append([op,tag])
            op = self.GetNextHierarchyObject(op)
        return found
    
    def _SetMaterials(self, data):
        """Set the materials attributes based on xml data.
        """
        nodes = self._GetNodes(data, self.MATERIAL)
        for node in nodes:
            if self._vrayMaterials:
                if c4d.GetCommandName(self.VRAY_CONVERTER) == "":
                    c4d.gui.MessageDialog("Vray not found")
                    return False
                c4d.CallCommand(self.VRAY_CONVERTER)
                c4d.DrawViews(c4d.DRAWFLAGS_FORCEFULLREDRAW)
            break
        self._initShaderArray()
        self._initMaterialArray()
        
        for node in nodes:
            self._SetMaterial(node)
            
    def _SetMaterial(self, node):
        """Set the material attributes based on xml data.
        """ 
        if node.hasAttribute(self.NAME):
        
            mats = self._GetMaterials(node.getAttribute(self.NAME))
            vray = False
            newMat = False
            
            if node.hasAttribute(self.VRAY):
                if node.getAttribute(self.VRAY).lower() == "true":
                    vray = True
            
            if len(mats)==0:
                #Create material that hasn't been imported
                if self._vrayMaterials:
                    mat = c4d.BaseMaterial(1020295)
                    mat.SetName("VR_"+str(node.getAttribute(self.NAME)))
                    mat[c4d.VRAYMATERIAL_COLOR1_MULT]=1
                    self._doc.InsertMaterial(mat)
                    mats.append(mat)
                    newMat = True
                elif self._usingOctane:
                    mat = c4d.BaseMaterial(1029501)
                    mat.SetName("OCT_"+str(node.getAttribute(self.NAME)))
                    self._doc.InsertMaterial(mat)
                    mats.append(mat)
                    newMat = True
                else:
                    mat = c4d.BaseMaterial(c4d.Mmaterial)
                    mat.SetName(str(node.getAttribute(self.NAME)))
                    self._doc.InsertMaterial(mat)
                    mats.append(mat)
                    newMat = True
            
            for mat in mats:
            
                self._initMaterial(mat)
                if not self._vrayMaterials and not self._usingOctane:
                    mat[c4d.MATERIAL_USE_TRANSPARENCY] = False
                    if self.R16:
                        #Setup R16 Standard(Vray->Std) Phong Reflection Early ( Has to be done this way )
                        base = c4d.REFLECTION_LAYER_LAYER_DATA + c4d.REFLECTION_LAYER_LAYER_SIZE * self.REFLECTION_LAYERID #Imported Specular Layer
                        mat[base+c4d.REFLECTION_LAYER_COLOR_BRIGHTNESS] = 0.7

                        mat[base+c4d.REFLECTION_LAYER_MAIN_DISTRIBUTION] = c4d.REFLECTION_DISTRIBUTION_PHONG
                        mat[base+c4d.REFLECTION_LAYER_MAIN_VALUE_REFLECTION] = 0.9 #Set Imported Specular Brightness to 100%
                        mat[base+c4d.REFLECTION_LAYER_MAIN_VALUE_SPECULAR] = 0.1 #Set Imported Specular Brightness to 100%
                    
                        mat[base+c4d.REFLECTION_LAYER_FRESNEL_MODE] = 0
                        
                        #mat[base+c4d.REFLECTION_LAYER_MAIN_VALUE_ROUGHNESSREAL] = 0.44
                
                if self._usingOctane:
                    oldMat = mat
                    mat = c4d.BaseMaterial(1029501)
                    mat.SetName("OCT_"+str(node.getAttribute(self.NAME)))
                    self._doc.InsertMaterial(mat)
                    
                    # Search for Reflective or Refractive Attributes to decide if Octane Diffuse, Glossy, or Specular Material..
                    isReflective = False
                    isRefractive = False
                    for attribute in self._materialAttributes:
                        if node.hasAttribute(attribute.name):
                            if (attribute.name=="vrayreflection_color" and node.getAttribute(attribute.name) != "0 0 0"):
                                isReflective = True
                            if (attribute.name=="vrayrefraction_color" and node.getAttribute(attribute.name) != "0 0 0"):
                                isRefractive = True
                    shaderNode = node.firstChild
                    while shaderNode:
                        if shaderNode.nodeType==1:
                            shaderType = shaderNode.getAttribute("shaderName").lower()
                            if (shaderType=="vrayreflection_map" or shaderType=="reflection_map"):
                                isReflective = True
                            if (shaderType=="vrayrefraction_map" or shaderType=="refraction_map"):
                                isRefractive = True                              
                        shaderNode = shaderNode.nextSibling
                    
                    if isRefractive:
                        mat[c4d.OCT_MATERIAL_TYPE] = 2513
                        absorptionShader = c4d.BaseShader(1029510)
                        mat.InsertShader(absorptionShader)
                        mat[c4d.OCT_MATERIAL_MEDIUM] = absorptionShader
                    elif isReflective:
                        mat[c4d.OCT_MATERIAL_TYPE] = 2511
                        mat[c4d.OCT_MATERIAL_INDEX] = 1
                    else:
                        mat[c4d.OCT_MATERIAL_TYPE] = 2510
                    
                self._SetMaterialAttributes(self._materialAttributes, node, mat)
                self._SetShaders(node, mat)
                
                if self._vrayMaterials:
                    #########################################################################################################################################
                    #########################################################################################################################################
                    #################################### VRAY MATERIALS #####################################################################################
                    #########################################################################################################################################
                    #########################################################################################################################################
                    if vray:
                        ##################################################################################################
                        ################# VRAY -> VRAY ###################################################################
                        ##################################################################################################
                        
                        ####################################################
                        #### REFLECTION ####################################
                        ####################################################
                        #Set up Reflection
                        mat[c4d.VRAYMATERIAL_SPECULAR1_TRACEREFL] = 1
                        mat[c4d.VRAYMATERIAL_SPECULAR1_COLOR_MULT] = 1


                        
                        ####################
                        ## IF NOT FRESNEL ##
                        ####################
                        
                        if not mat[c4d.VRAYMATERIAL_SPECULAR1_USEFRESNEL]:
                            #Set Spec Transp to White
                            mat[c4d.VRAYMATERIAL_SPECULAR1_TRANSP] = c4d.Vector(1,1,1)
                            mat[c4d.VRAYMATERIAL_SPECULAR1_TRANSP_MULT] = 1


                            #Max RGB Energy Preservation mode equates to Spec color subtracted from Diffuse color..
                            
                            #Create Fusion shader in Spec Transp Shader slot
                            fShader = c4d.BaseShader(1011109)
                            
                            #Fusion Base is Diffuse Color/Map:
                            if mat[c4d.VRAYMATERIAL_COLOR1_SHADER]:
                                ##Recreate Color Shader in Fusion Base Slot
                                shaderNodes = node.getElementsByTagName("shader")
                                shaderNode = node.firstChild
                                shaderTypeInt = None
                                while shaderNode:
                                    if shaderNode.nodeType==1:
                                        if shaderNode.getAttribute("shaderName") == "diffuse_map":
                                            #Just Using 'normal_normal_map' as it uses access to fusion base
                                            shaderNode.setAttribute("shaderName","normal_normal_map")
                                            self._SetShaders(node, fShader, nodeName="normal_normal_map")
                                            shaderNode.setAttribute("shaderName","diffuse_map")
                                    shaderNode = shaderNode.nextSibling
                            else:
                                ##Else use Diffuse color                                
                                bColorShader = c4d.BaseShader(5832)
                                bColorShader[c4d.COLORSHADER_COLOR] =  mat[c4d.VRAYMATERIAL_COLOR1_COLOR]
                                fShader.InsertShader(bColorShader)
                                fShader[c4d.SLA_FUSION_BASE_CHANNEL] = bColorShader #BASE CHANNEL#
                            
                            if mat[c4d.VRAYMATERIAL_SPECULAR1_SHADER]:
                                ##Recreate Spec Shader in Fusion Blend Slot
                                shaderNodes = node.getElementsByTagName("shader")
                                shaderNode = node.firstChild
                                shaderTypeInt = None
                                while shaderNode:
                                    if shaderNode.nodeType==1:
                                        if shaderNode.getAttribute("shaderName") == "reflection_map":
                                            #Just Using 'normal_bump_map' as it uses access to fusion blend
                                            shaderNode.setAttribute("shaderName","normal_bump_map") 
                                            self._SetShaders(node, fShader, nodeName="normal_bump_map")
                                            shaderNode.setAttribute("shaderName","reflection_map") 
                                    shaderNode = shaderNode.nextSibling
                            else:
                                #Else use Specular color
                                blColorShader = c4d.BaseShader(5832)
                                blColorShader[c4d.COLORSHADER_COLOR] = mat[c4d.VRAYMATERIAL_SPECULAR1_COLOR]
                                fShader.InsertShader(blColorShader)
                                fShader[c4d.SLA_FUSION_BLEND_CHANNEL] = blColorShader #BLEND CHANNEL#
                            
                            #Set Fusion shader to Subtract mode
                            fShader[c4d.SLA_FUSION_MODE] = 2011
                            #hsv = colorsys.rgb_to_hsv(mat[c4d.VRAYMATERIAL_SPECULAR1_COLOR][0], mat[c4d.VRAYMATERIAL_SPECULAR1_COLOR][1], mat[c4d.VRAYMATERIAL_SPECULAR1_COLOR][2])
                            mat.InsertShader(fShader)
                            mat[c4d.VRAYMATERIAL_SPECULAR1_TRANSPSHADER] = fShader
                            mat[c4d.VRAYMATERIAL_SPECULAR1_TRANSPTEXMULT] = 1#hsv[2]
                            mat.Message(c4d.MSG_UPDATE)
                            mat.Update(True,True)
                        
                        ####################################################
                        #### REFRACTION ####################################
                        ####################################################
                        #Set up Refraction
                        refrcolor = mat[self.VRAY_REFR_COLOR][0]+mat[self.VRAY_REFR_COLOR][1]+mat[self.VRAY_REFR_COLOR][2]
                        if refrcolor == 0.0 and mat[self.VRAY_WEIGHT_SHADER]==None:
                            #If Refraction color is pure black or no texture, disable channel
                            mat[self.VRAY_USE_WEIGHT] = 0
                        else:
                            #Set up C4D Vray Refraction
                            #Set Diffuse Transparency Color to Refraction Color, and set Refraction to White.
                            mat[c4d.VRAYMATERIAL_COLOR1_TRANSP] = mat[self.VRAY_REFR_COLOR]
                            mat[c4d.VRAYMATERIAL_COLOR1_TRANSP_MULT] = 1
                            mat[self.VRAY_REFR_COLOR] = c4d.Vector(1,1,1)
                            mat[self.VRAY_REFR_COLORMULT] = 1
                            #Set Specular Transparency Shader Mix Amount to Diffuse Transparency Color Brightness.
                            hsv = colorsys.rgb_to_hsv(mat[c4d.VRAYMATERIAL_COLOR1_TRANSP][0], mat[c4d.VRAYMATERIAL_COLOR1_TRANSP][1], mat[c4d.VRAYMATERIAL_COLOR1_TRANSP][2])
                            mat[c4d.VRAYMATERIAL_SPECULAR1_TRANSPTEXMULT] = 1-hsv[2]
                        ####################################################
                        #### LUMINANCE #####################################
                        ####################################################
                        #Fixes max luminance - if lum color is pure black or no texture, disable channel
                        lumcolor = mat[c4d.VRAYMATERIAL_LUMINANCE_COLOR][0]+mat[c4d.VRAYMATERIAL_LUMINANCE_COLOR][1]+mat[c4d.VRAYMATERIAL_LUMINANCE_COLOR][2]
                        if lumcolor == 0.0 and mat[c4d.VRAYMATERIAL_LUMINANCE_SHADER]==None:
                            mat[c4d.VRAYMATERIAL_USE_LUMINANCE] = 0
                        #if node.hasAttribute('vraylightmultiplier'):
                        #    mat[c4d.VRAYMATERIAL_USE_COLOR1] = False
                        #    mat[c4d.VRAYMATERIAL_USE_SPECULAR1] = False
                        ####################################################
                        #### ALPHA OPACITY #################################
                        ####################################################
                        #Fixes opacity conversion, invert vray weight channel in c4d
                        if mat[self.VRAY_USE_REFRACTION]:
                            mat[self.VRAY_WEIGHT_TEXINVERT] = 1
                        ####################################################
                        #### BUMP ======####################################
                        ####################################################
                        #Ivert VRay Bump in c4d and divide amount by 100
                        if mat[c4d.VRAYMATERIAL_USE_BUMP]:
                            mat[c4d.VRAYMATERIAL_BUMP_BUMPTEXINVERT] = 1
                            mat[c4d.VRAYMATERIAL_BUMP_BUMPTEXMULT] /= 100
                    else:
                        ##################################################################################################
                        ################# STANDARD -> VRAY ###############################################################
                        ##################################################################################################
                        
                        ####################################################
                        #### REFLECTION ####################################
                        ####################################################
                        #Set up Reflection
                        mat[c4d.VRAYMATERIAL_SPECULAR1_TRANSP_MULT] = 0
                        if self._stdReflectionChanged:
                            mat[c4d.VRAYMATERIAL_SPECULAR1_TRACEREFL] = 1
                            self._stdReflectionChanged = False
                        else:
                            mat[c4d.VRAYMATERIAL_SPECULAR1_TRACEREFL] = 0
                        
                        ####################################################
                        #### LUMINANCE #####################################
                        ####################################################
                        #Set up Luminance channel based on xml std mat SelfIllumAmount value
                        if mat[c4d.VRAYMATERIAL_USE_LUMINANCE]:
                        
                            if mat[c4d.VRAYMATERIAL_LUMINANCE_COLOR_MULT] > 0:
                                mat[c4d.VRAYMATERIAL_LUMINANCE_COLOR_MULT] /= 100 #DIVIDE BY 100 BASED ON MY ASSUMED XML VALUE OF 100
                                mat[c4d.VRAYMATERIAL_LUMINANCE_COLOR] = mat[c4d.VRAYMATERIAL_COLOR1_COLOR]
                                if mat[c4d.VRAYMATERIAL_COLOR1_SHADER]:
                                    shaderDest = XmlMaterialAttribute("",c4d.VRAYMATERIAL_LUMINANCE_SHADER,None)
                                    for shaderInf in self._shaderTypes:
                                        if shaderInf.name == "bitmap":
                                            shaderTypeInt = shaderInf.desc
                                    for shaderInf in self._vrayShaderAttributes:
                                        if shaderInf.shaderName == "filename":
                                            shaderAttr = shaderInf
                                    shader = self._shaderFunc(shaderDest,shaderTypeInt,mat,False)
                                    self._bitmapShaderFunc(shaderAttr,mat[c4d.VRAYMATERIAL_COLOR1_SHADER][1000],shader)
                                    # shader = c4d.BaseShader(1026701)
                                    #For some reason, channel shader doesn't update/affect unless we loop through it to set shader type to VrayAdvBitmap - who knows.
                                    # l=0
                                    # while l<11:
                                        # try:
                                            # shader[c4d.VRAY_SHADERS_LIST] = l
                                            # if shader[4997] == "TexXSIBitmap":
                                                # break
                                        # except AttributeError:
                                            # pass
                                        # l+=1
                                    # cont = shader.GetDataInstance()
                                    #cont.SetReal(89981969,0.45454545) #Set gamma back to normal as it uses 2.2 by default --DISABLED UNTIL FURTHER CONFIRMATION--
                                    # cont.SetFilename(4999,mat[c4d.VRAYMATERIAL_COLOR1_SHADER][1000])
                                    # mat[c4d.VRAYMATERIAL_LUMINANCE_SHADER] = shader
                                    # mat.InsertShader(shader)
                                    
                                #This is commented out, cos it fucks up
                                #mat[c4d.VRAYMATERIAL_LUMINANCE_TRANSP] = c4d.Vector(255,255,255)
                                #mat[c4d.VRAYMATERIAL_LUMINANCE_TRANSP_MULT] = 1
                            else:
                                mat[c4d.VRAYMATERIAL_USE_LUMINANCE] = False
                        ####################################################
                        #### ALPHA OPACITY #################################
                        ####################################################
                        #Fix when std mats converted to vray mat - puts opacity into Refraction shader slot, so swap this to weight channel
                        #We haven't implemented refraction shader, so if it exists, remove it:
                        if mat[self.VRAY_WEIGHT_SHADER] is not None:
                            mat[self.VRAY_WEIGHT_SHADER] = None
                        # if mat[self.VRAY_USE_WEIGHT]:
                            # if mat[self.VRAY_WEIGHT_SHADER] == None:
                                # mat[self.VRAY_USE_REFRACTION] = True
                                # mat[self.VRAY_WEIGHT_SHADER] = mat[self.VRAY_WEIGHT_SHADER]
                                # mat[self.VRAY_WEIGHT_TEXINVERT] = 1
                                # mat[self.VRAY_USE_WEIGHT] = False
                                # mat[self.VRAY_WEIGHT_SHADER] = None
                        # else:
                            #If refraction channel is empty, that means no opacity map, so disable actual weight channel ( in case it's enabled, like when there's a tga with alpha in the diffuse )
                            # Would be better if it took account of the Max opacity amount value not just map, but need opacity info in xml for that.
                            # mat[self.VRAY_USE_REFRACTION] = False
                            # mat[self.VRAY_WEIGHT_SHADER] = None
                        
                        #Fix when std mats converted to vray mat - diffuse transparency colour is white, change to black
                        #[c4d.VRAYMATERIAL_COLOR1_TRANSP] = c4d.Vector(0,0,0)
                    
                    #Switch off Specular layer 4+2, getting switched on for no reason.
                    mat[c4d.VRAYMATERIAL_USE_SPECULAR2] = False
                    mat[c4d.VRAYMATERIAL_USE_SPECULAR3] = False
                    mat[c4d.VRAYMATERIAL_USE_SPECULAR4] = False
                    mat[c4d.VRAYMATERIAL_USE_SPECULAR5] = False
                    mat[c4d.VRAYMATERIAL_USE_REFLECTION] = False
                
                elif self._usingOctane:
                    print ""#"_SetMaterial ( Set Octane Material Stuff )"
                
                else:
                    #########################################################################################################################################
                    #########################################################################################################################################
                    #################################### STANDARD MATERIALS #################################################################################
                    #########################################################################################################################################
                    #########################################################################################################################################
                    
                    #################################################
                    ##### ALL STANDARD MATS #########################
                                                                   ##
                    mat[c4d.MATERIAL_REFLECTION_ADDITIVE] = True   ##
                                                                   ##
                    #################################################
                    #################################################
                    
                    if vray:
                        ##################################################################################################
                        ################# VRAY -> STANDARD ###############################################################
                        ##################################################################################################
                        
                        if not self.R16:
                            ####################################################################################
                            #### R15 VRAY ######################################################################
                            ####################################################################################
                            mat[c4d.MATERIAL_TRANSPARENCY_BRIGHTNESS] = 1
                            if mat[c4d.MATERIAL_REFLECTION_COLOR]:
                                mat[c4d.MATERIAL_SPECULAR_COLOR] = mat[c4d.MATERIAL_REFLECTION_COLOR]
                                
                                if mat[self.STD_LOCKGLOSS]:
                                    mat[c4d.MATERIAL_SPECULAR_WIDTH] = mat[c4d.MATERIAL_REFLECTION_DISPERSION]
                            mat[c4d.MATERIAL_SPECULAR_HEIGHT] = 1
                            #mat[c4d.MATERIAL_SPECULAR_WIDTH] = 0.5
                            mat[c4d.MATERIAL_SPECULAR_BRIGHTNESS] = 1
                            #mat[c4d.MATERIAL_USE_ENVIRONMENT] = 0
                            if node.hasAttribute('vraylightmultiplier'):
                                mat[c4d.MATERIAL_USE_COLOR] = False
                                mat[c4d.MATERIAL_USE_SPECULAR] = False
                        else:
                            ####################################################################################
                            #### R16 VRAY ######################################################################
                            ####################################################################################
                            #Transparency Brightness is set to 0% on r16 for no reason..
                            mat[c4d.MATERIAL_TRANSPARENCY_BRIGHTNESS] = 1
                            ####################################################
                            #### REFLECTION ####################################
                            ####################################################
                            #Set up Reflection
                            #mat[c4d.VRAYMATERIAL_SPECULAR1_TRACEREFL] = 1
                            base = c4d.REFLECTION_LAYER_LAYER_DATA + c4d.REFLECTION_LAYER_LAYER_SIZE * self.REFLECTION_LAYERID #Imported Specular Layer
                            #mat[base+c4d.REFLECTION_LAYER_MAIN_VALUE_REFLECTION] = 0.3
                    else:
                        ##################################################################################################
                        ################# STANDARD -> STANDARD ###########################################################
                        ##################################################################################################
                        
                        if not self.R16:
                            ####################################################################################
                            #### R15 STANDARD ##################################################################
                            ####################################################################################
                            if mat[c4d.MATERIAL_SPECULAR_BRIGHTNESS]:
                                mat[c4d.MATERIAL_SPECULAR_HEIGHT] = mat[c4d.MATERIAL_SPECULAR_BRIGHTNESS]
                            if mat[c4d.MATERIAL_USE_TRANSPARENCY] and mat[c4d.MATERIAL_ALPHA_SHADER]==None:
                                mat[c4d.MATERIAL_USE_ALPHA] = True
                                mat[c4d.MATERIAL_ALPHA_SHADER] = mat[c4d.MATERIAL_TRANSPARENCY_SHADER]
                                mat[c4d.MATERIAL_USE_TRANSPARENCY] = False
                                
                            mat[c4d.MATERIAL_SPECULAR_BRIGHTNESS] = 1
                            mat[c4d.MATERIAL_USE_ENVIRONMENT] = 0
                            mat[c4d.MATERIAL_SPECULAR_HEIGHT] = 0.1
                            mat[c4d.MATERIAL_SPECULAR_WIDTH] = 0.5
                            
                            mat[c4d.MATERIAL_REFLECTION_ADDITIVE] = 1
                            mat[c4d.MATERIAL_TRANSPARENCY_BRIGHTNESS] = 1
                            mat[c4d.MATERIAL_USE_DIFFUSION] = 0
                        else:
                            ####################################################################################
                            #### R16 STANDARD ##################################################################
                            ####################################################################################
                            base = c4d.REFLECTION_LAYER_LAYER_DATA + c4d.REFLECTION_LAYER_LAYER_SIZE * self.REFLECTION_LAYERID #Imported Specular Layer
                            #mat[base+c4d.REFLECTION_LAYER_MAIN_VALUE_REFLECTION] = 1
                            
                    
                    if self._quickMode:
                        mat[c4d.MATERIAL_REFLECTION_DISPERSION] = 0
                        mat[c4d.MATERIAL_TRANSPARENCY_DISPERSION] = 0
                
                mat.Message(c4d.MSG_UPDATE)
                mat.Update(True, True)
    
    def _trawlContainer(self, cont):
        l=0
        #print "-------------------"
        while cont.GetIndexId(l) != -1:
            subID = cont.GetIndexId(l)
            try:
                #print cont[subID]
                if subID == c4d.REFLECTION_LAYER_GLOBAL_SPECULAR:
                    print "isCONTAINER"
                    self._trawlContainer(cont[subID])
            except AttributeError:
                pass
            
            #print cont.GetType(subID)
            #if cont is c4d.BaseContainer():
                #self._trawlContainer(cont[subID])
            #else:
                #print cont
            #self._trawlContainer(cont[subID])
            #print "Obj = "+str(subID)+" = "+str(cont.GetType(subID))+" = "+str(cont[subID])
            #print "Obj = "+str(subID)+" = "+str(cont[subID].GetTypeName())+" = "+str(cont[subID])
            l+=1
    
    def _GetMaterials(self, name):
        """Return materials named 'name'.
        """
        found = []
        materials = self._doc.GetMaterials()
        for mat in materials:
            matName = mat.GetName()
            if self._vrayMaterials:
                if ("VR_"+name) == matName or ("VR_BLEND"+name) == matName or ("VR_TWOSIDED"+name) == matName or ("VR_OVERRIDE"+name) == matName:
                    found.append(mat)
            else:
                if name == matName:
                    found.append(mat)
        return found
    
    def _GetMaterialsUtil(self, name, doc=_doc):
        """Return materials named 'name'.  VERSION WITHOUT ADDING VR_
        """
        found = []
        if (doc==None):
            doc = self._doc
        materials = doc.GetMaterials()
        for mat in materials:
            if mat.GetName().lower() == name.lower():
                found.append(mat)
        return found
        
    def _initMaterial(self, mat):
        """Init the material before change settings.
        """
        # Disable channels
#         channels = self._stdChannels if mat.GetType() == c4d.Mmaterial else self._vrayChannels
#         for channel in channels:
#             mat[channel] = False
        # Set mix mode to normal
        if mat.GetType() == c4d.Mmaterial:
            mat[c4d.MATERIAL_COLOR_TEXTUREMIXING] = c4d.MATERIAL_TEXTUREMIXING_NORMAL
    
    def _SetMaterialAttributes(self, attributesTab, node, container):
        """Set the xml material attributes.
        """
        for attribute in attributesTab:
            if node.hasAttribute(attribute.name):
                
                data = node.getAttribute(attribute.name)
                
                if attribute.vrayConvert:
                    data = attribute.vrayConvert(attribute, data)
                
                if attribute.setFunction:
                    if not self._vrayMaterials and not self._usingOctane:
                        #if attribute.setFunction.func_name=="_r16reflectance" or attribute.setFunction.func_name=="_r15fresnel":
                        if attribute.setFunction.func_name=="_r15fresnel":
                            attribute.setFunction(attribute, data, container, node)
                        else:
                            attribute.setFunction(attribute, data, container)
                    else:
                        if self._usingOctane:
                            if attribute.name=="vrayrefraction_color":
                                if container[c4d.OCT_MATERIAL_MEDIUM]:
                                    attribute.setFunction(attribute, data, container[c4d.OCT_MATERIAL_MEDIUM])
                            elif attribute.name=="color":
                                if container[c4d.OCT_MATERIAL_EMISSION]:
                                    attribute.setFunction(attribute, data, container[c4d.OCT_MATERIAL_EMISSION])
                            elif attribute.name=="multiplier":
                                if container[c4d.OCT_MATERIAL_EMISSION]:
                                    attribute.setFunction(attribute, data, container[c4d.OCT_MATERIAL_EMISSION])
                            else:
                                attribute.setFunction(attribute, data, container)
                        else:
                            attribute.setFunction(attribute, data, container)
                
                if attribute.use:
                    container[attribute.use] = True
                
                container.Message(c4d.MSG_UPDATE)
            else:
                try:
                    if container[attribute.desc]:
                        try:
                            #The XML doesn't have this attribute so check if the material has a bitmap in there that shouldn't be there..
                            dontRun = True
                            if not dontRun:
                                if container[attribute.desc].GetType()==5833:
                                    inXML = False
                                    for attributeSearch in attributesTab:
                                        #Search for that parameter desc elsewhere in the XML
                                        if attributeSearch.desc==attribute.desc:
                                            if node.hasAttribute(attributeSearch.name):
                                                if not node.hasAttribute(attributeSearch.name):
                                                    self._ThrowError()
                                                inXML = True
                                    #If there's a bitmap here then remove it cos it isn't in the xml
                                    if not inXML:
                                        container[attribute.desc] = None
                        except AttributeError:
                            pass
                except IndexError:
                    pass
    
    def _SetShaders(self, node, mat, nodeName=None,sub=False,parent=None):
        """Set the xml material tags.
        """
        #print "######## CREATING SHADERS ################"
        shaderNodes = node.getElementsByTagName("shader")
        shaderNode = node.firstChild
        shaderTypeInt = None
        while shaderNode:
            if shaderNode.nodeType==1:
                #Either do all or just individual shader node
                if nodeName==None or shaderNode.getAttribute("shaderName").lower()==nodeName.lower():
                    vray=False
                    for shaderType in self._shaderTypes:
                        if shaderNode.getAttribute("type").lower()==shaderType.name.lower():
                            shaderTypeInt = shaderType.desc
                            if shaderType.vrayAttribute:
                                vray=True
                            shaderDest = None
                            if self._vrayMaterials:
                                shaderAttributes = self._vrayShaderAttributes
                            else:
                                shaderAttributes = self._shaderAttributes
                            for shaderDestAttr in self._materialAttributes:
                                if shaderNode.getAttribute("shaderName").lower()==shaderDestAttr.name.lower():
                                    if shaderNode.getAttribute("type")=="Normal_Bump" and not self._vrayMaterials:
                                        if shaderDestAttr.use:
                                            mat[c4d.MATERIAL_USE_NORMAL] = True
                                        shaderDest = XmlMaterialAttribute(shaderDestAttr.name,c4d.MATERIAL_NORMAL_SHADER,None)
                                    else:
                                        if shaderDestAttr.use:
                                            mat[shaderDestAttr.use] = True
                                        shaderDest = XmlMaterialAttribute(shaderDestAttr.name,shaderDestAttr.desc,None)
                                    parentType = "mat"
                            if shaderDest is None:
                                for shaderDestAttrSub in shaderAttributes:
                                    if shaderNode.getAttribute("shaderName").lower()==shaderDestAttrSub.shaderName.lower():
                                        print "shaderDestAttrSub.shaderName = "+shaderDestAttrSub.shaderName
                                        shaderDest = XmlMaterialAttribute(shaderDestAttrSub.shaderName,shaderDestAttrSub.desc,None)   
                                        parentType = "shader"
                            if shaderDest:
                                if shaderDest.desc==c4d.VRAYMATERIAL_SPECULAR1_SHADER:
                                    self._stdReflectionChanged = True
                                isNormalRamp=False
                                if "mat" in mat.GetTypeName().lower():
                                    self.currentMat = mat
                                    self.currentSlot = shaderDest
                                if shaderType.name=="CompositeTexturemap":
                                    self._RecreateCompositeShader(shaderNode,shaderDest,mat,parentType,vray)
                                elif shaderType.name=="Gradient_Ramp":
                                    self._RecreateGradientShader(shaderNode,shaderDest,mat,vray)
                                elif shaderType.name=="Normal_Bump":
                                    self._RecreateNormalShader(shaderNode,shaderDest,mat,vray)
                                elif shaderType.name=="VRayMap":
                                    self._RecreateVrayRefRaf(shaderNode,shaderDest,mat)
                                else:
                                    print "     shaderType = "+shaderType.name
                                    doFusion = False
                                    print "Creating "+shaderType.name+" in "+mat.GetName()+"("+shaderDest.name+" / "+str(shaderDest.desc)+" )"
                                    if mat[shaderDest.desc] is not None and mat[shaderDest.desc].GetName() != "Bitmap":
                                        #If existing shader in slot, mix in Fusion shader..
                                        print "     Existing Shader in Slot - Creating Fusion"
                                        if self._vrayMaterials:
                                            fusionShader = c4d.BaseList2D(self.VRAYSHADER) #VRAY MIX SHADER#
                                            fusionShader[c4d.VRAY_SHADERS_LIST] = 29
                                            fusionShader[114886856] = mat[shaderDest.desc] #BASE CHANNEL#
                                            fusionShaderDest = XmlMaterialAttribute("",114886956,None) #BLEND CHANNEL#
                                        else:
                                            fusionShader = c4d.BaseShader(1011109)
                                            fusionShader[c4d.SLA_FUSION_MODE] = 2001
                                            fusionShader[c4d.SLA_FUSION_BASE_CHANNEL] = mat[shaderDest.desc]
                                            fusionShaderDest = XmlMaterialAttribute("",c4d.SLA_FUSION_BLEND_CHANNEL,None)
                                        fusionShader.SetName("Existing_"+shaderNode.getAttribute("name"))
                                        print "     Creating Shader in Fusion"
                                        shader = self._shaderFunc(fusionShaderDest,shaderTypeInt,fusionShader,vray)
                                        mat.InsertShader(fusionShader)
                                        mat[shaderDest.desc] = fusionShader
                                        doFusion = True
                                    else:
                                        print "     No Existing Shader in Slot - Creating Shader"
                                        shader = self._shaderFunc(shaderDest,shaderTypeInt,mat,vray)
                                        print "     Shader = "+str(shader)
                                    
                                    if shaderType.name == "Bitmaptexture":
                                        subNode = shaderNode.firstChild
                                        while subNode:
                                            if subNode.nodeType==1:
                                                if subNode.hasAttribute("paramName"):
                                                    if subNode.getAttribute("paramName") == "Output":
                                                        if subNode.hasAttribute("output_invert"):
                                                            if subNode.getAttribute("output_invert") == "true":
                                                                if self._vrayMaterials:
                                                                    shader[107820086] = True
                                                                else:
                                                                    shader[c4d.BITMAPSHADER_BLACKPOINT] = 1
                                                                    shader[c4d.BITMAPSHADER_WHITEPOINT] = 0
                                            subNode = subNode.nextSibling
                                        bitmapfilename = shaderNode.getAttribute("filename")
                                        fileTypeString = bitmapfilename[len(bitmapfilename)-3:len(bitmapfilename)]
                                        if fileTypeString == "psd" and self._vrayMaterials:
                                            #If it's a psd file and vraymaterial, insert in a Filter shader to discard alpha info
                                            if self._vrayMaterials:
                                                filterShader = c4d.BaseList2D(self.VRAYSHADER) #VRAY CC SHADER#
                                                filterShader[c4d.VRAY_SHADERS_LIST] = 7
                                            else:
                                                filterShader = c4d.BaseShader(1011128)
                                            mat[shaderDest.desc] = None
                                            if doFusion:
                                                if self._vrayMaterials:
                                                    fusionShader = c4d.BaseList2D(self.VRAYSHADER) #VRAY MIX SHADER#
                                                    fusionShader[c4d.VRAY_SHADERS_LIST] = 29
                                                    fusionShader[72354685] = 6 #BLENDMODE MULTIPLY#
                                                    fusionShader[114886856] = shader #BASE CHANNEL#
                                                    fusionShaderDest = XmlMaterialAttribute("",114886956,None)
                                                    shader = self._shaderFunc(fusionShaderDest,shaderTypeInt,fusionShader,vray)
                                                    filterShader[76821548] = fusionShader
                                                else:
                                                    fusionShader = c4d.BaseShader(1011109)
                                                    fusionShader[c4d.SLA_FUSION_MODE] = 2019
                                                    fusionShader[c4d.SLA_FUSION_BASE_CHANNEL] = shader
                                                    fusionShaderDest = XmlMaterialAttribute("",c4d.SLA_FUSION_BLEND_CHANNEL,None)
                                                    shader = self._shaderFunc(fusionShaderDest,shaderTypeInt,fusionShader,vray)
                                                    filterShader[c4d.SLA_FILTER_TEXTURE] = fusionShader
                                                mat.InsertShader(filterShader)
                                                mat[shaderDest.desc] = filterShader
                                            else:
                                                if self._vrayMaterials:
                                                    filterShaderDest = XmlMaterialAttribute("",76821548,None)
                                                else:
                                                    filterShaderDest = XmlMaterialAttribute("",c4d.SLA_FILTER_TEXTURE,None)
                                                shader = self._shaderFunc(filterShaderDest,shaderTypeInt,filterShader,vray)
                                                mat.InsertShader(filterShader)
                                                mat[shaderDest.desc] = filterShader
                                        elif fileTypeString == "tga" or fileTypeString == "png":
                                            if self.currentSlot.desc == c4d.VRAYMATERIAL_TRANSP_SHADER:
                                                if not self._vrayMaterials:
                                                    if shader.GetType() == c4d.Xbitmap:
                                                        shader = c4d.BaseShader(c4d.Xbitmap)
                                                        bc = shader.GetDataInstance()
                                                        bc.SetFilename(1000,bitmapfilename)
                                                        bc.SetReal(c4d.BITMAPSHADER_WHITEPOINT,0.0001)
                                                        mat.InsertShader(shader)
                                                        mat[shaderDest.desc] = shader
                                                    else:
                                                        shader = c4d.BaseShader(c4d.Xbitmap)
                                                        bc = shader.GetDataInstance()
                                                        bc.SetFilename(1000,bitmapfilename)
                                                        bc.SetReal(c4d.BITMAPSHADER_WHITEPOINT,0.0001)
                                                        mat.InsertShader(shader)
                                                        mat[shaderDest.desc] = shader
                                    
                                    shaderName = mat.GetName()+"_"+shaderDest.name+"_"+shaderType.name+"_"+shaderNode.getAttribute("name")
                                    shader.SetName(shaderNode.getAttribute("name"))
                                    bc = shader.GetDataInstance()
                                    for shaderAttr in shaderAttributes:
                                        if shaderNode.hasAttribute(shaderAttr.shaderName):
                                            if not shaderNode.hasAttribute(shaderAttr.shaderName):
                                                self._ThrowError()
                                            data = shaderNode.getAttribute(shaderAttr.shaderName)
                                            if shader.GetType()==1011109 or shaderAttr.setFunction==self._colorToColorShaderFunc:
                                                shaderAttr.setFunction(shaderAttr, data, shader)
                                            else:
                                                shaderAttr.setFunction(shaderAttr, data, shader)
                                    #@Check if MSG_UPDATE is slowing it down
                                    shader.Message(c4d.MSG_UPDATE)
                                    self._SetShaders(shaderNode, shader, sub=True, parent=shader.GetName())
                                    #shader[c4d.VRAY_SHADERS_LIST] = shaderType
                                    if shaderType.desc==48:
                                        #If Cellular, set Density to 10
                                        shader[10355708] = 10
                                    if shaderDest.name=="mix_mask":
                                        mat[c4d.SLA_FUSION_BLEND] = 100
            shaderNode = shaderNode.nextSibling
    
    def _RecreateVrayOutput(self,node,shaderDest,mat):
        #If no shader plugged into Output shader, just create a white color#
        hasShader = False
        shaderNodes = node.getElementsByTagName("shader")
        shaderNode = node.firstChild
        while shaderNode:
            if shaderNode.nodeType==1:
                if shaderNode.hasAttribute("shaderName"):
                    filterShader = c4d.BaseShader(1011128)
                    mat.InsertShader(filterShader)
                    mat[shaderDest.desc] = filterShader
                    #self._SetShaders(shaderNode.parentNode, filterShader)
                    self._SetShaders(shaderNode.parentNode, filterShader)
                    hasShader = True
            shaderNode = shaderNode.nextSibling
        if not hasShader:
            colorShader = c4d.BaseShader(5832) #PARENT SHADER OR DIFFUSE/CHANNEL COLOR#
            colorShader[c4d.COLORSHADER_COLOR] = c4d.Vector(1,1,1)
            mat.InsertShader(colorShader)
            mat[shaderDest.desc] = colorShader
            
    def _RecreateVrayRefRaf(self,node,shaderDest,mat):
        if shaderDest.desc==c4d.VRAYMATERIAL_SPECULAR1_SHADER:
            if node.getAttribute("vrrefraf_refraf")=="0":
                #Is ReflectMode
                if node.getAttribute("vrrefraf_reflglossyon")=="false":
                    #mat[c4d.VRAYMATERIAL_SPECULAR1_HIGHLIGHTGLOSS] = 1
                    mat[c4d.VRAYMATERIAL_SPECULAR1_REFLECTIONGLOSS] = 1
                else:
                    glossyAmount = float(node.getAttribute("vrrefraf_reflglossy"))/100
                    #mat[c4d.VRAYMATERIAL_SPECULAR1_HIGHLIGHTGLOSS] = glossyAmount
                    mat[c4d.VRAYMATERIAL_SPECULAR1_REFLECTIONGLOSS] = 1-glossyAmount
                components = node.getAttribute("vrrefraf_reflcolor").split()
                mat[c4d.VRAYMATERIAL_SPECULAR1_COLOR] = c4d.Vector(int(components[0]), int(components[1]), int(components[2])) / 255.0
                mat[c4d.VRAYMATERIAL_SPECULAR1_COLOR_MULT] = 1
                mat[c4d.VRAYMATERIAL_SPECULAR1_USEFRESNEL] = False
                if node.hasAttribute("vrrefraf_reflmap") and node.getAttribute("vrrefraf_reflmapon")=="true":
                    mat[c4d.VRAYMATERIAL_SPECULAR1_SHADER] = node.getAttribute("vrrefraf_reflmap")
        if shaderDest.desc==c4d.MATERIAL_REFLECTION_SHADER:
            if node.getAttribute("vrrefraf_refraf")=="0":
                #Is ReflectMode
                if node.getAttribute("vrrefraf_reflglossyon")=="false":
                    mat[c4d.MATERIAL_REFLECTION_DISPERSION] = 0
                else:
                    glossyAmount = float(node.getAttribute("vrrefraf_reflglossy"))/100
                    mat[c4d.MATERIAL_REFLECTION_DISPERSION] = glossyAmount
                components = node.getAttribute("vrrefraf_reflcolor").split()
                mat[c4d.MATERIAL_REFLECTION_COLOR] = c4d.Vector(int(components[0]), int(components[1]), int(components[2])) / 255.0
                mat[c4d.MATERIAL_REFLECTION_BRIGHTNESS] = 1
                if node.hasAttribute("vrrefraf_reflmap") and node.getAttribute("vrrefraf_reflmapon")=="true":
                    mat[c4d.MATERIAL_REFLECTION_SHADER] = node.getAttribute("vrrefraf_reflmap")
        shaderNodes = node.getElementsByTagName("shader")
        shaderNode = node.firstChild
        while shaderNode:
            if shaderNode.nodeType==1:
                self._SetShaders(shaderNode.parentNode, mat, nodeName=shaderNode.getAttribute("shaderName"))
            shaderNode = shaderNode.nextSibling
        
    def _RecreateNormalShader(self,node,shaderDest,mat,vray):
        if self._vrayMaterials:
            # shader = self._shaderFunc(shaderDest,29,mat,vray) #Create Fusion
            shader = self._shaderFunc(shaderDest,1011109,mat,vray) #Create Fusion
        else:
            shader = self._shaderFunc(shaderDest,1011109,mat,vray) #Create Fusion
        
        shaderName = mat.GetName()+"_"+shaderDest.name+"_"+"Fresnel"+"_"+node.getAttribute("name")
        shader.SetName(shaderName)
        
        if vray:
            shaderAttributes = self._vrayShaderAttributes
        else:
            shaderAttributes = self._shaderAttributes
        
        shaderNodes = node.getElementsByTagName("shader")
        shaderNode = node.firstChild
        while shaderNode:
            if shaderNode.nodeType==1:
                self._SetShaders(shaderNode.parentNode, shader, nodeName=shaderNode.getAttribute("shaderName"))
            shaderNode = shaderNode.nextSibling
        
        bumpAmt = float(node.getAttribute("normal_bump_spin"))
        normalAmt = float(node.getAttribute("normal_mult_spin"))
        
        if normalAmt >= bumpAmt:
            blendAmt = 1*(bumpAmt/normalAmt)
        else:
            blendAmt = 1
        
        if self._vrayMaterials:
            # shader[72354685] = 6 #BLENDMODE MULTIPLY#
            # if shader[c4d.SLA_FUSION_BLEND_CHANNEL] is not None and node.getAttribute("normal_map2on")=="true":
                # shader[114797471] = c4d.Vector(blendAmt,blendAmt,blendAmt)
            # else:
                # shader[114797471] = c4d.Vector(0,0,0)
            shader[c4d.SLA_FUSION_MODE] = 2019 #BLENDMODE MULTIPLY#
            if shader[c4d.SLA_FUSION_BLEND_CHANNEL] is not None and node.getAttribute("normal_map2on")=="true":
                shader[c4d.SLA_FUSION_BLEND] = blendAmt
            else:
                shader[c4d.SLA_FUSION_BLEND] = 0
        else:
            shader[c4d.SLA_FUSION_MODE] = 2019 #BLENDMODE MULTIPLY#
            if shader[c4d.SLA_FUSION_BLEND_CHANNEL] is not None and node.getAttribute("normal_map2on")=="true":
                shader[c4d.SLA_FUSION_BLEND] = blendAmt
            else:
                shader[c4d.SLA_FUSION_BLEND] = 0
        
        if shaderDest.desc==c4d.VRAYMATERIAL_BUMP_SHADER: 
            if node.getAttribute("normal_method")=="Tangent":
                mat[c4d.VRAYMATERIAL_BUMP_TYPE] = 1
        elif shaderDest.desc==c4d.MATERIAL_NORMAL_SHADER:
            if node.getAttribute("normal_flipred")=="true":
                mat[c4d.MATERIAL_NORMAL_REVERSEX] = True
            if node.getAttribute("normal_flipgreen")=="true":
                mat[c4d.MATERIAL_NORMAL_REVERSEY] = True
            if node.getAttribute("normal_swap_rg")=="true":
                mat[c4d.MATERIAL_NORMAL_SWAP] = True
        
    def _RecreateCompositeShader(self,node,shaderDest,mat,parentType,vray):
        
        #print "####### CREATING COMPOSITE ###############"
        
        #assetDoc = c4d.documents.LoadDocument(self._pluginPath+"/Assets/Vray.c4d", c4d.SCENEFILTER_MATERIALS)
        #tempMat = (self._GetMaterialsUtil("LayeredShader",assetDoc))[0]
        #master_layeredShader = tempMat[c4d.VRAYMATERIAL_COLOR1_SHADER].GetClone()
        
        shaderNodes = node.getElementsByTagName("shader")
        shaderNode = node.firstChild
        colorFound = False
        prevLayer = None
        alreadyInserted = False
        
        # If Composite is being created directly in a material slot, try and find the associated color for that channel, and mix with it in a fusion.
        
        ammendedMapName = self.currentSlot.name.replace("map","")+"color"
        
        for matAttr in self._materialAttributes:
            if matAttr.name == ammendedMapName:
                prevLayer = c4d.BaseShader(5832) #PARENT SHADER OR DIFFUSE/CHANNEL COLOR#
                prevLayer[c4d.COLORSHADER_COLOR] = self.currentMat[matAttr.desc]
                colorFound = True
        #if not colorFound:
            #print "Nope - Cant find = "+ammendedMapName
        
        if prevLayer is None:
            prevLayer = c4d.BaseShader(5832) #PARENT SHADER OR DIFFUSE/CHANNEL COLOR#
            prevLayer[c4d.COLORSHADER_COLOR] = c4d.Vector(0,0,0) ##Couldn't source Parent, using color Black instead##
        
        prevLayer.SetName("ChannelBase");
        prevLayer.Message(c4d.MSG_UPDATE)
        mapNum = 1
        while shaderNode:
            if shaderNode.nodeType==1:
                if "map" in shaderNode.getAttribute("shaderName"):
                    # print "shaderNode = "+str(shaderNode.getAttribute("shaderName"))
                    mapEnabled = self._truefalseToBool(node.getAttribute("composite_mapEnabled"+str(mapNum)))
                    if mapEnabled:
                        fusionShader = c4d.BaseShader(1011109)
                        fusionShader.InsertShader(prevLayer)
                        fusionShader.SetName(shaderDest.name)
                        fusionShader[c4d.SLA_FUSION_BASE_CHANNEL] = prevLayer
                        fusionShader.SetName("Map"+str(mapNum)) 
                        maskEnabled = self._truefalseToBool(node.getAttribute("composite_maskEnabled"+str(mapNum)))
                        if maskEnabled:
                            maskNode = node.firstChild
                            while maskNode:
                                if maskNode.nodeType==1:
                                    if str("mask"+str(mapNum)) in maskNode.getAttribute("shaderName"):
                                        self._SetShaders(shaderNode.parentNode, fusionShader,maskNode.getAttribute("shaderName"))
                                        fusionShader[c4d.SLA_FUSION_USE_MASK] = True
                                maskNode = maskNode.nextSibling
                        fusionShader[c4d.SLA_FUSION_BLEND] = float(node.getAttribute("composite_opacity"+str(mapNum)))/100
                        self._SetShaders(shaderNode.parentNode, fusionShader, nodeName=shaderNode.getAttribute("shaderName"))
                        if mapNum>0:
                            attr = XmlShaderAttribute("composite_blendMode"+str(mapNum),c4d.SLA_FUSION_MODE,None)
                            data = shaderNode.parentNode.getAttribute("composite_blendMode"+str(mapNum))
                            self._shaderStrTypeFunc(attr, data, fusionShader.GetDataInstance())
                        fusionShader.Message(c4d.MSG_UPDATE)
                        prevLayer = fusionShader
                    mapNum+=1
                #
            shaderNode = shaderNode.nextSibling
        
        mat.InsertShader(prevLayer)
        mat[shaderDest.desc] = prevLayer
    
    def _RecreateGradientShader(self,node,shaderDest,mat,vray):
        fresnelGrad = False
        if self._vrayMaterials:
            # shaderTypeInt = 37 #Create VrayGradient
            # if node.getAttribute("ramp_gradientType")=="Normal":
                # fresnelGrad = True
            if node.getAttribute("ramp_gradientType")=="Normal":
                fresnelGrad = True
                shaderTypeInt = 1011103 #Create FresnelShader
            else:
                shaderTypeInt = 1011100 #Create Gradient
        else:
            if node.getAttribute("ramp_gradientType")=="Normal":
                fresnelGrad = True
                shaderTypeInt = 1011103 #Create FresnelShader
            else:
                shaderTypeInt = 1011100 #Create Gradient
        shader = self._shaderFunc(shaderDest,shaderTypeInt,mat,vray)
        shaderName = mat.GetName()+"_"+shaderDest.name+"_"+"Gradient"+"_"+node.getAttribute("name")
        shader.SetName(shaderName)
        if vray:
            shaderAttributes = self._vrayShaderAttributes
        else:
            shaderAttributes = self._shaderAttributes
        
        if node.getAttribute("ramp_gradientType")!="Normal":
            for shaderAttr in shaderAttributes:
                if "ramp_Flag_Color" not in shaderAttr.shaderName:
                    if node.hasAttribute(shaderAttr.shaderName):
                        #Set other attributes except Flag colors
                        data = node.getAttribute(shaderAttr.shaderName)
                        shaderAttr.setFunction(shaderAttr, data, shader)
        # else:
            # if self._vrayMaterials:
                # shader[264317982] = 6
        
        if self._vrayMaterials:
            # bc = shader.GetDataInstance()
            # gradient = bc[9100]
            if fresnelGrad:
                gradient = shader[c4d.SLA_FRESNEL_GRADIENT]
            else:
                gradient = shader[c4d.SLA_GRADIENT_GRADIENT]
        else:
            if fresnelGrad:
                gradient = shader[c4d.SLA_FRESNEL_GRADIENT]
            else:
                gradient = shader[c4d.SLA_GRADIENT_GRADIENT]
        gradient.FlushKnots()
        gradient.SetData(c4d.GRADIENT_INTERPOLATION,c4d.GRADIENT_INTERPOLATION_LINEARKNOT)
        maxFlags = 12
        curKnot = 0
        for i in xrange(maxFlags):
            hasPos = False
            pos = 0
            attrName = "ramp_Flag_Color"+str(i)+"_pos"
            if node.hasAttribute(attrName):
                pos = node.getAttribute(attrName)
                hasPos = True
            attrName = "ramp_Flag_Color"+str(i)
            if node.hasAttribute(attrName):
                data = node.getAttribute(attrName)
                components = data[1:len(data)-1].split(",")
                data = c4d.Vector(float(components[0]), float(components[1]), float(components[2])) / 255.0
                if not hasPos:
                    if i == 1:
                        pos = 0
                    else:
                        pos = 1
                else:
                    pos = float(pos)/100
                gradient.InsertKnot(col=data,pos=pos,brightness=1)
                curKnot += 1
        if self._vrayMaterials:
            # bc[9100] = gradient
            if fresnelGrad:
                shader[c4d.SLA_FRESNEL_GRADIENT] = gradient
            else:
                shader[c4d.SLA_GRADIENT_GRADIENT] = gradient
        else:
            if fresnelGrad:
                shader[c4d.SLA_FRESNEL_GRADIENT] = gradient
            else:
                shader[c4d.SLA_GRADIENT_GRADIENT] = gradient
        shader.Message(c4d.MSG_UPDATE)
        
    def _SetColors(self, data):
        """Set the wire color attributes based on xml data.
        """
        nodes = self._GetNodes(data, self.GEOMETRY)
        for node in nodes:
            if node.hasAttribute(self.WIRECOLOR):
                self._SetColor(node.getAttribute(self.NAME).lower(), node.getAttribute(self.WIRECOLOR))
    
    def _SetTurboSmooth(self, data):
        """Applies Hypernurbs is there's a TurboSmooth value in geometry xml
        """
        nodes = self._GetNodes(data, self.GEOMETRY)
        for node in nodes:
            if node.hasAttribute("turbosmooth"):
                obj = self._doc.SearchObject(node.getAttribute("name"))
                if obj is not None:
                    subdivs = c4d.BaseObject(1007455)
                    subdivs[c4d.SDSOBJECT_SUBEDITOR_CM] = int(node.getAttribute("turbosmooth_vp"))
                    subdivs[c4d.SDSOBJECT_SUBRAY_CM] = int(node.getAttribute("turbosmooth"))
                    subdivs[c4d.SDSOBJECT_SUBDIVIDE_UV] = 2002
                    subdivs.SetName("SD_"+obj.GetName())
                    self._doc.InsertObject(subdivs,pred=obj)
                    obj.InsertUnder(subdivs)
                else:
                    print "Turbosmooth Not Applied to - "+node.getAttribute("name")
    
    def _SetVrayProxyObjects(self, data):
        """Creates VrayProxy objects from XML and applies Materials
        """
        nodes = self._GetNodes(data, self.VRAYPROXY)
        for node in nodes:
            if node.hasAttribute("filename"):
                vrProxy = c4d.BaseObject(1021309)
                
                parentName = node.getAttribute("parent")
                foundParent = False
                if (parentName!="undefined"):
                    parentObj = self._doc.SearchObject(parentName)
                    if parentObj is not None:
                        foundParent = True
                if foundParent:
                    vrProxy.InsertUnder(parentObj)
                else:
                    self._doc.InsertObject(vrProxy)
                
                vrProxy[c4d.VRAYPROXY_FILE] = str(node.getAttribute("filename"))
                vrProxy[c4d.VRAYPROXY_SCALE] = 1
                bc = vrProxy.GetData()
                bc.SetFilename(c4d.VRAYPROXY_FILE, str(node.getAttribute("filename")))
                vrProxy.SetData(bc)
                
                vrProxy.Message(c4d.MSG_UPDATE)
                c4d.EventAdd()
    
    def _SetVrayProxyObjects2(self):
        
        removeList = []
        op = self._doc.GetFirstObject()
        while op:
            if (op.GetName()[:7] == "PROXYS_"):
                instanceObject = c4d.BaseObject(5126)
                masterName = "PROXYM_"+op.GetName()[7:(op.GetName().rfind("_"))]
                masterObject = self._doc.SearchObject(masterName)
                if (masterObject is not None):
                    instanceObject[c4d.INSTANCEOBJECT_LINK] = masterObject
                    instanceObject[c4d.INSTANCEOBJECT_RENDERINSTANCE] = True
                    instanceName = op.GetName()
                    removeList.append(op)
                    instanceObject.SetName(instanceName+"0")
                    instanceObject.SetAbsPos(op.GetAbsPos())
                    instanceObject.SetAbsRot(op.GetAbsRot())
                    instanceObject.SetAbsScale(op.GetAbsScale())
                    self._doc.InsertObject(instanceObject)
            op = self._GetNextHierarchyObject(op)
        
        for ob in removeList:
            ob.Remove()
    
    def _SetBackground(self, data):
        """Setup background Sky object based on xml data.
        """
        nodes = self._GetNodes(data, "background")
        
        if not self._vrayMaterials and not self._usingOctane:
            skyObj = c4d.BaseObject(c4d.Osky)
            skyObj.SetRelRot(c4d.Vector(c4d.utils.Rad(90),0,0))
            self._doc.InsertObject(skyObj)
            skyObj.SetEditorMode(c4d.MODE_OFF)
        
        for node in nodes:
            colorNode = node.getElementsByTagName("color")
            for subnode in colorNode:
                if subnode.hasAttribute("value"):
                    components = subnode.getAttribute("value").split()
                    bgcolor = c4d.Vector(int(components[0]), int(components[1]), int(components[2]))
                    if self._usingOctane:
                        c4d.CallCommand(1033866, 1033866) #Create OctaneSky With RGB Map
                        skyTag = self._doc.GetActiveObject().GetTags()[0]
                        skyTag[c4d.ENVIRONMENTTAG_TEXTURE][c4d.RGBSPECTRUMSHADER_COLOR] = bgcolor
                        skyTag[c4d.ENVTAG_VISIBLE_ENVIRONMENT] = True
                        
                    elif self._vrayMaterials:
                        rd = self._doc.GetActiveRenderData()
                        vp = self._GetVrayVideoPost(rd)
                        bc = vp.GetData()
                        bc[c4d.VP_VRAYBRIDGE_ENVIRONMENT_BACKGROUND] = bgcolor / 255.0
                        usemap=False
                        usemapNode = node.getElementsByTagName("usemap")
                        for subnode in usemapNode:
                            if subnode.hasAttribute("value"):
                                if subnode.getAttribute("value")=="true":
                                    usemap=True
                        if usemap:
                            mat = c4d.BaseMaterial(c4d.Mmaterial)
                            self._SetShaders(node,mat)
                            if (mat[c4d.MATERIAL_COLOR_SHADER] is not None):
                                shader = mat[c4d.MATERIAL_COLOR_SHADER].GetClone()
                                mat[c4d.MATERIAL_COLOR_SHADER] = None
                                vp.InsertShader(shader)
                                bc[c4d.VP_VRAYBRIDGE_ENVIRONMENT_BACKGROUNDTEX] = shader
                        maptypeNode = node.getElementsByTagName("mappingtype")
                        for mapSub in maptypeNode:
                            if mapSub.hasAttribute("value"):
                                mappingType = mapSub.getAttribute("value")
                                if mappingType=="Spherical Environment" or mappingType =="Spherical":
                                    vp[c4d.VP_VRAYBRIDGE_ENVIRONMENT_BGMAPTYPE]=2
                                elif mappingType=="Angular":
                                    bc[c4d.VP_VRAYBRIDGE_ENVIRONMENT_BGMAPTYPE]=0
                                else:
                                    bc[c4d.VP_VRAYBRIDGE_ENVIRONMENT_BGMAPTYPE]=4
                        intensityNodes = node.getElementsByTagName("rendermult")
                        intensity = 1.0
                        for intensityNode in intensityNodes:
                            if intensityNode.hasAttribute("value"):
                                intensity = float(intensityNode.getAttribute("value"))
                                bc[c4d.VP_VRAYBRIDGE_ENVIRONMENT_BGMAPMUL]=intensity/3
                        intensityNodes2 = node.getElementsByTagName("rendermult_mapoutput")
                        for intensityNode2 in intensityNodes2:
                            if intensityNode2.hasAttribute("value"):
                                intensity2 = float(intensityNode2.getAttribute("value"))*intensity
                                bc[c4d.VP_VRAYBRIDGE_ENVIRONMENT_BGMAPMUL]=intensity2
                        intensityNodes3 = node.getElementsByTagName("gamma")
                        for intensityNode3 in intensityNodes3:
                            if intensityNode3.hasAttribute("value"):
                                intensity3 = float(intensityNode3.getAttribute("value"))*intensity2
                                bc[c4d.VP_VRAYBRIDGE_ENVIRONMENT_BGMAPMUL]=intensity3
                        hrotNodes = node.getElementsByTagName("hrot")
                        for hrotNode in hrotNodes:
                            if hrotNode.hasAttribute("value"):
                                rot = float(hrotNode.getAttribute("value"))*-1
                                bc[c4d.VP_VRAYBRIDGE_ENVIRONMENT_BGMAPROTH]=c4d.utils.Rad(rot+90)
                        #VRot is different in c4d, disabled
                        # vrotNodes = node.getElementsByTagName("vrot")
                        # for vrotNode in vrotNodes:
                            # if vrotNode.hasAttribute("value"):
                                # rot = float(vrotNode.getAttribute("value"))
                                # bc[c4d.VP_VRAYBRIDGE_ENVIRONMENT_BGMAPROTP]=c4d.utils.Rad(rot)
                        vp.SetData(bc)
                        vp.Message(c4d.MSG_UPDATE)
                    else:
                        color = self._SetColor(skyObj.GetName(), subnode.getAttribute("value"))
                        usemapNode = node.getElementsByTagName("usemap")
                        for subnode in usemapNode:
                            if subnode.hasAttribute("value"):
                                usemap = subnode.getAttribute("value")
                                if (usemap!="true"):
                                    return
                                maptypeNode = node.getElementsByTagName("mappingtype")
                                for subnode in maptypeNode:
                                    if subnode.hasAttribute("value"):
                                        mappingType = subnode.getAttribute("value")
                                        mappathNode = node.getElementsByTagName("mappath")
                                        for subnode in mappathNode:
                                            if subnode.hasAttribute("value"):
                                                path = subnode.getAttribute("value")
                                                
                                                mat1 = c4d.BaseMaterial(c4d.Mmaterial)
                                                mat1[c4d.MATERIAL_USE_COLOR]=0
                                                mat1[c4d.MATERIAL_USE_SPECULAR]=0
                                                mat1[c4d.MATERIAL_USE_LUMINANCE]=1
                                                
                                                bitmapShader = c4d.BaseShader(c4d.Xbitmap)
                                                bitmapShader[c4d.BITMAPSHADER_FILENAME]=str(path)
                                                
                                                mat1[c4d.MATERIAL_LUMINANCE_SHADER]=bitmapShader
                                                mat1.InsertShader(bitmapShader)
                                                
                                                self._doc.InsertMaterial(mat1)
                                                
                                                textag = c4d.BaseTag(c4d.Ttexture)
                                                textag.SetMaterial(mat1)
                                                if (mappingType=="Spherical Environment"):
                                                    textag[c4d.TEXTURETAG_PROJECTION]=c4d.TEXTURETAG_PROJECTION_SPHERICAL
                                                else:
                                                    textag[c4d.TEXTURETAG_PROJECTION]=c4d.TEXTURETAG_PROJECTION_FRONTAL
                                                skyObj.InsertTag(textag);
            
    def _SetColor(self, name, color):
        op = self._doc.GetFirstObject()
        while op:
            if op.GetName().lower() == name.lower():
                op[c4d.ID_BASEOBJECT_USECOLOR]=1
                colList = [float(s) for s in color.split() if s.isdigit()]
                colVect = c4d.Vector()
                colVect.x = colList[0]/255
                colVect.y = colList[1]/255
                colVect.z = colList[2]/255
                
                op[c4d.ID_BASEOBJECT_COLOR]=colVect
                
            op = self._GetNextHierarchyObject(op)
    
    def _SetMatteObjects(self,data):
        nodes = self._GetNodes(data, "matte_object")
        for node in nodes:
            if node.hasAttribute("name"):
                obj = self._doc.SearchObject(node.getAttribute("name"))
                if obj:
                    if self._vrayLights:
                        tag = c4d.BaseTag(1021738)
                        tag[c4d.VRAYCOMPOSITINGTAG_MATTE] = True
                        tag[c4d.VRAYCOMPOSITINGTAG_MATTESHADOWS] = True
                        tag[c4d.VRAYCOMPOSITINGTAG_MATTESHADOWALPHA] = True
                        tag[c4d.VRAYCOMPOSITINGTAG_MATTEALPHACONTRIB] = -1
                        tag[c4d.VRAYCOMPOSITINGTAG_REFLVIS] = False
                        ntag = obj.GetTag(c4d.Ttexture)
                        if ntag!=None:
                                obj.KillTag(c4d.Ttexture)
                        obj.InsertTag(tag)
                        obj.Message(c4d.MSG_UPDATE)
                    else:
                        tag = c4d.BaseTag(5637)
                        tag[c4d.COMPOSITINGTAG_SEENBYREFLECTION] = False
                        tag[c4d.COMPOSITINGTAG_BACKGROUND] = True
                        tag[c4d.COMPOSITINGTAG_BACKGROUND_GI] = True
                        objTags = obj.GetTags()
                        obj.Message(c4d.MSG_UPDATE)
                        i=0
                        for ttag in objTags:
                            if ttag.GetType() == c4d.Ttexture:
                                if ttag.GetName() == "Texture":
                                    obj.KillTag(c4d.Ttexture,i-1)
                                elif ttag.GetMaterial().GetName() != ttag.GetName():
                                    matteMat = self._GetMaterials(ttag.GetName())
                                    if len(matteMat) != 0:
                                        matteMat[0][c4d.MATERIAL_USE_COLOR] = False
                                        matteMat[0][c4d.MATERIAL_USE_TRANSPARENCY] = False
                                        matteMat[0][c4d.MATERIAL_USE_REFLECTION] = False
                                        matteMat[0][c4d.MATERIAL_USE_ENVIRONMENT] = False
                                        matteMat[0][c4d.MATERIAL_USE_SPECULAR] = False
                                        matteMat[0][c4d.MATERIAL_USE_LUMINANCE] = True
                                        ttag.SetMaterial(matteMat[0])
                            i+=1
                        obj.InsertTag(tag)
    
    def _SetLights(self, data):
        """Set the lights attributes based on xml data.
        """
        nodes = self._GetNodes(data, self.LIGHT)
        for node in nodes:
            if self._vrayLights:
                if c4d.GetCommandName(self.VRAY_CONVERTER) == "":
                    c4d.gui.MessageDialog("Vray not found")
                    return False
            break
        self._initLightArray()
        
        lights = self._GetStdLights()
        
        for node in nodes:
            self._SetLight(node)
        
    def _SetLight(self, node):
        """Set the light attributes based on xml data.
        """ 
        if node.hasAttribute(self.NAME):
            lights = self._GetLights(node.getAttribute(self.NAME))
            vray = False
            shadowon = False
            if node.hasAttribute("v_shadow"):
                if node.getAttribute("v_shadow").lower() == "true":
                    shadowon = True
            if node.hasAttribute(self.VRAY):
                if node.getAttribute(self.VRAY).lower() == "true":
                    vray = True
            for light in lights:
                
                if not vray:
                    #If it's a standad max light - if its <r16 and a target light, rotate 90 degrees / if the xml has a hotspot value, then apply to 'beam' value for parallel lights
                    if self._vrayLights:
                        light.GetTag(self.VRAY_LIGHT_TAG)[c4d.VRAYLIGHTTAG_COMMON_INTENSITY] *= 10000
                    if node.hasAttribute("hotspot"):
                        if self._vrayLights:
                            light.GetTag(self.VRAY_LIGHT_TAG)[c4d.VRAYLIGHTTAG_COMMON_BEAMRADIUS] = float(node.getAttribute("hotspot"))
                        else:
                            light[c4d.LIGHT_DETAILS_OUTERRADIUS] = float(node.getAttribute("hotspot"))
                    if node.hasAttribute("target") and not self.R16:
                        if node.getAttribute("target")=="true":
                            a = 2 #rotation axis
                            light[c4d.ID_BASEOBJECT_ROTATION_ORDER] = 0
                            rotVec = light.GetRelRot()
                            rot = c4d.utils.Deg(rotVec[a])+90
                            rotVec[a] = c4d.utils.Rad(rot)
                            light.SetRelRot(rotVec)
                            light[c4d.ID_BASEOBJECT_ROTATION_ORDER] = 6
                tag = None
                if self._vrayLights and vray and light.GetTag(self.VRAY_LIGHT_TAG) is None:
                    tag = c4d.BaseTag(self.VRAY_LIGHT_TAG)
                    light.InsertTag(tag)
                    light.Message(c4d.MSG_UPDATE)
                    c4d.DrawViews(c4d.DRAWFLAGS_ONLY_ACTIVE_VIEW|c4d.DRAWFLAGS_NO_THREAD|c4d.DRAWFLAGS_NO_REDUCTION|c4d.DRAWFLAGS_STATICBREAK)
                if self._usingOctane and light.GetTag(self.OCTANE_LIGHT_TAG) is None:
                    light[c4d.LIGHT_TYPE] = 8
                    tag = c4d.BaseTag(self.OCTANE_LIGHT_TAG)
                    tag[c4d.LIGHTTAG_VIS_CAM] = False
                    light.InsertTag(tag)
                    light.Message(c4d.MSG_UPDATE)
                    c4d.DrawViews(c4d.DRAWFLAGS_ONLY_ACTIVE_VIEW|c4d.DRAWFLAGS_NO_THREAD|c4d.DRAWFLAGS_NO_REDUCTION|c4d.DRAWFLAGS_STATICBREAK)
                if shadowon:
                    if self._quickMode:
                        light[c4d.LIGHT_SHADOWTYPE] = c4d.LIGHT_SHADOWTYPE_SOFT
                    else:
                        light[c4d.LIGHT_SHADOWTYPE] = c4d.LIGHT_SHADOWTYPE_AREA
                
                if self._vrayLights:
                    self._SetLightAttributes(self._vrayLightAttributes, node, light)
                    if light[c4d.LIGHT_PHOTOMETRIC_INTENSITY] > 6000:
                        light[c4d.LIGHT_PHOTOMETRIC_INTENSITY] = 6000
                    if tag is not None:
                        if tag[c4d.VRAYLIGHTTAG_COMMON_LIGHTTYPE] == 2:
                            #If Vray Sun Light#
                            rd = self._doc.GetActiveRenderData()
                            vp = self._GetVrayVideoPost(rd)
                            if vp[c4d.VP_VRAYBRIDGE_ENVIRONMENT_BACKGROUNDTEX] is not None:
                                tag[c4d.VRAYLIGHTTAG_SUN_SKYBG] = False
                                tag[c4d.VRAYLIGHTTAG_SUN_SKYREFL] = False
                                tag[c4d.VRAYLIGHTTAG_SUN_SKYREFR] = False
                elif self._usingOctane:
                    self._SetLightAttributes(self._octLightAttributes, node, light)
                else:
                    self._SetLightAttributes(self._lightAttributes, node, light)
                if not self._usingOctane and not self._vrayLights and vray:
                    #light[c4d.LIGHT_AREADETAILS_SHOWINRENDER] = True
                    light[c4d.LIGHT_AREADETAILS_SHOWINREFLECTION] = True
    
    def _SetLightAttributes(self, attributesTab, node, container):
        """Set the xml light attributes.
        """
        for attribute in attributesTab:
            if node.hasAttribute(attribute.name):
                data = node.getAttribute(attribute.name)
                if attribute.vrayAttribute and self._vrayLights:
                    vrayTag = container.GetTag(self.VRAY_LIGHT_TAG)
                    attribute.setFunction(attribute, data, vrayTag)
                    vrayTag[c4d.VRAYLIGHTTAG_AREA_SUBDIVS] = 8
                    vrayTag[c4d.VRAYLIGHTTAG_COMMON_SHDSUBDIVS] = 8
                    vrayTag.Message(c4d.MSG_UPDATE)
                elif self._usingOctane:
                    octaneTag = container.GetTag(self.OCTANE_LIGHT_TAG)
                    attribute.setFunction(attribute, data, octaneTag)
                    octaneTag.Message(c4d.MSG_UPDATE)
                
                else:
                    if attribute.vrayConvert:
                        data = attribute.vrayConvert(attribute, data)
                    attribute.setFunction(attribute, data, container)
                    container.Message(c4d.MSG_UPDATE)
    
    def _SetCameras(self, data):
        """Set the camera attributes based on xml data.
        """
        nodes = self._GetNodes(data, self.CAMERA)
        for node in nodes:
            if node.hasAttribute(self.VRAY):
                if node.getAttribute(self.VRAY).lower() == "true":
                    if self._vrayCameras:
                        if c4d.GetCommandName(self.VRAY_CONVERTER) == "":
                            c4d.gui.MessageDialog("Vray not found")
                            return False
                    break
        self._initCamArray()
        for node in nodes:
            self._SetCamera(node)
        
        tempCam = self._GetCameras("TempCam")
        if len(tempCam)!=0:
            self._doc.GetActiveBaseDraw().SetSceneCamera(tempCam[0])
            cam = tempCam[0]
            #if self.R16:
            #R16 rotates temp cam 90 degrees, so fix that
            a = 1 #rotation axis
            cam[c4d.ID_BASEOBJECT_ROTATION_ORDER] = 0
            rotVec = cam.GetRelRot()
            rot = c4d.utils.Deg(rotVec[a])+90
            rotVec[a] = c4d.utils.Rad(rot)
            cam.SetRelRot(rotVec)
            cam[c4d.ID_BASEOBJECT_ROTATION_ORDER] = 6
            if self._vrayCameras and cam.GetTag(self.VRAY_CAMERA_TAG) is None:
                tag = c4d.BaseTag(self.VRAY_CAMERA_TAG)
                #Std->Vraycam - Set shutterspeed to 5
                tag[c4d.VRAYPHYSICALCAMERATAG_SHUTTERSPEED] = 8
                #Set WhiteBalance to White until we implement into XML
                tag[c4d.VRAYPHYSICALCAMERATAG_WHITEBALANCE] = c4d.Vector(1,1,1)
                cam.InsertTag(tag)
                cam.Message(c4d.MSG_UPDATE)
        
        if self._doc.GetActiveBaseDraw().SetSceneCamera() == None:
            op = self._doc.GetFirstObject()
            while op:
                if op.GetType() == c4d.Ocamera:
                    self._doc.GetActiveBaseDraw().SetSceneCamera(op)
                op = self._GetNextHierarchyObject(op)
        
        op = self._doc.GetFirstObject()
        while op:
            if (op.GetName()[:7] == "CAMPOS_"):
                cams = self._GetCameras(op.GetName()[7:])
                if (cams[0] is not None):
                    cams[0].SetAbsPos(op.GetAbsPos())
                    boxRot = op.GetAbsRot()
                    cams[0].SetAbsRot(boxRot)
                    op.Remove()
            op = self.GetNextHierarchyObject(op)
        
    def _SetCamera(self, node):
        """Set the light attributes based on xml data.
        """ 
        if node.hasAttribute(self.NAME):
            cameras = self._GetCameras(node.getAttribute(self.NAME))
            vray = False
            if node.hasAttribute(self.VRAY):
                if node.getAttribute(self.VRAY).lower() == "true":
                    vray = True
            for cam in cameras:
                if self._vrayCameras and cam.GetTag(self.VRAY_CAMERA_TAG) is None:
                    tag = c4d.BaseTag(self.VRAY_CAMERA_TAG)
                    if not vray:
                        #Std->Vraycam - Set shutterspeed to 5
                        tag[c4d.VRAYPHYSICALCAMERATAG_SHUTTERSPEED] = 8
                    #Set WhiteBalance to White until we implement into XML
                    tag[c4d.VRAYPHYSICALCAMERATAG_WHITEBALANCE] = c4d.Vector(1,1,1)
                    cam.InsertTag(tag)
                    cam.Message(c4d.MSG_UPDATE)
                if self._usingOctane and cam.GetTag(self.OCTANE_CAMERA_TAG) is None:
                    tag = c4d.BaseTag(self.OCTANE_CAMERA_TAG)
                    cam.InsertTag(tag)
                    cam.Message(c4d.MSG_UPDATE)
                # if not self._vrayCameras:
                    # rd = self._doc.GetActiveRenderData()
                    # rd[c4d.RDATA_RENDERENGINE] = 1023342
                    # cam[c4d.CAMERAOBJECT_EXPOSURE] = True
                    # if not vray:
                        # cam[c4d.CAMERAOBJECT_ISO_VALUE] = 100
                        # cam[c4d.CAMERAOBJECT_FNUMBER_VALUE] = 8
                        # cam[c4d.CAMERAOBJECT_SHUTTER_SPEED_VALUE] = 0.125
                
                self._SetCameraAttributes(self._camAttributes, node, cam)
                 
                if self._vrayCameras and cam.GetTag(self.VRAY_CAMERA_TAG):
                    self._SetCameraAttributes(self._camAttributes, node, tag)
                    if node.hasAttribute("vignetting"):
                        if node.getAttribute("vignetting").lower()=="false":
                            tag[c4d.VRAYPHYSICALCAMERATAG_VIGNETTING] = 0
                
                camTags = cam.GetTags()
                isTargetCam = False
                
                for ttag in camTags:
                    if ttag.GetType() == 5676: #KILL TARGET TAGS#
                        isTargetCam = True
                        cam.KillTag(5676)
         
    def _SetCameraAttributes(self, attributesTab, node, container):
        """Set the xml camera attributes.
        """
        for attribute in attributesTab:
            if node.hasAttribute(attribute.name):
                data = node.getAttribute(attribute.name)
                if attribute.vrayAttribute and self._vrayCameras:
                    vrayTag = container.GetTag(self.VRAY_CAMERA_TAG)
                    attribute.setFunction(attribute, data, vrayTag)
                    vrayTag.Message(c4d.MSG_UPDATE)
                else:
                    if attribute.vrayConvert:
                        data = attribute.vrayConvert(attribute, data)
                    attribute.setFunction(attribute, data, container)
                    container.Message(c4d.MSG_UPDATE)
   
    def _GetCameras(self, name):
        """Return cameras named 'name'.
        """
        found = []
        op = self._doc.GetFirstObject()
        while op:
            if op.GetName().lower() == name.lower():
                if op.GetType() == c4d.Onull:
                    op = self._NullToCam(op)
                if op.GetType() == c4d.Ocamera:
                    found.append(op)
            op = self._GetNextHierarchyObject(op)
        return found
    
    def GetNextHierarchyObject(self, op):
        """Return the next object in hierarchy.
        """
        if op is None:
            return None
        down = op.GetDown()
        if down:
            return down
        next = op.GetNext()
        if next:
            return next
        prev = op.GetUp()
        while prev:
            next = prev.GetNext()
            if next:
                return next
            prev = prev.GetUp()    
        return None
    
    def _cleanPolygonObjects(self, doc):
        
        op = doc.GetFirstObject()
        
        while op:
            if op.GetType() == c4d.Opolygon:
                
                doc.AddUndo(c4d.UNDOTYPE_CHANGE, op)
                
                # phong
                if (self.CB_AP_CURRENT):
                    op.SetPhong(True, True, c4d.utils.Rad(self.NUM_PA_CURRENT))
                    tags = op.GetTags()
                    for tag in tags:
                        if tag.GetType()==c4d.Tphong:
                            tag[c4d.PHONGTAG_PHONG_USEEDGES] = False
                
                # optimize
                if (self.CB_OP_CURRENT):
                    bc = c4d.BaseContainer()
                    bc[c4d.MDATA_OPTIMIZE_POINTS] = True
                    bc[c4d.MDATA_OPTIMIZE_TOLERANCE] = 0.01
                    bc[c4d.MDATA_OPTIMIZE_UNUSEDPOINTS] = True
                    bc[c4d.MDATA_OPTIMIZE_POLYGONS] = True
                    res = utils.SendModelingCommand(
                        command = c4d.MCOMMAND_OPTIMIZE,
                        list = [op],
                        mode = c4d.MODELINGCOMMANDMODE_ALL,
                        bc = bc,
                        doc = doc)
                    c4d.EventAdd(c4d.MSG_UPDATE)
                
                # untriangulate
                if (self.CB_UT_CURRENT):
                    bc = c4d.BaseContainer()
                    bc[c4d.MDATA_UNTRIANGULATE_ANGLE] = True
                    bc[c4d.MDATA_UNTRIANGULATE_ANGLE_RAD] = self.NUM_EA_CURRENT
                    res = utils.SendModelingCommand(
                        command = c4d.MCOMMAND_UNTRIANGULATE,
                        list = [op],
                        mode = c4d.MODELINGCOMMANDMODE_ALL,
                        bc = bc,
                        doc = doc)
                    c4d.EventAdd(c4d.MSG_UPDATE)
                    
            op = self.GetNextHierarchyObject(op)
    
    def _applyMultiSubMatsCorrectly(self, doc):
        """Search all texture tags and if has Selection and material applied isn't same as selection name ( default assignment for unrecognised materials on export from max ) then apply corrent mats
        """
        op = self._doc.GetFirstObject()
        while op:
            tags = op.GetTags()
            for tag in tags:
                if tag.GetType()==5616:
                    #If texture tag
                    tagSelection = tag[c4d.TEXTURETAG_RESTRICTION]
                    if tagSelection:
                        if self.R16:
                            if self._vrayMaterials:
                                
                                selName = "VR_"+tagSelection
                            elif self._usingOctane:
                                selName = "OCT_"+tagSelection
                            else:
                                selName = tagSelection
                        else:
                            if self._vrayMaterials:
                                selName = "VR_"+tagSelection[0:len(tagSelection)-10]
                            elif self._usingOctane:
                                selName = "OCT_"+tagSelection[0:len(tagSelection)-10]
                            else:
                                selName = tagSelection[0:len(tagSelection)-10]
                        matName = tag.GetMaterial().GetName()
                        if selName!=matName:
                            replace = True
                            for ignoreMat in self._tagMatsDoNotReplace:
                                if matName==ignoreMat:
                                    replace = False
                            if replace:
                                newMat = self._GetMaterialsUtil(selName)
                                try:
                                    tag.SetMaterial(newMat[0])
                                except IndexError:
                                    pass
                    else:
                        #If No Selection then just check if the mat matches the tag name
                        tagName = tag.GetName()
                        matName = tag.GetMaterial().GetName()
                        if self._usingOctane:
                            tagName = "OCT_"+tagName
                        if "BLEND" not in matName and "OVERRIDE" not in matName and "TWOSIDED" not in matName:
                            #Not special mat..
                            if tagName not in matName:
                                #print "WRONG matName = "+matName+" / "+tagName
                                if self._vrayMaterials:
                                    newMat = self._GetMaterialsUtil("VR_"+tagName)
                                elif self._usingOctane:
                                    newMat = self._GetMaterialsUtil(tagName)
                                else:
                                    newMat = self._GetMaterialsUtil(tagName)
                                try:
                                    tag.SetMaterial(newMat[0])
                                except IndexError:
                                    pass
                            
                        
            op = self._GetNextHierarchyObject(op)
    
    def _applyBlendSubmats(self,parentTag,blendNode,obj):
        #print "applyBlendSubmats"
        allBlendNodes = self._GetNodes(self._data, "blendmaterial")
        allMatNodes = self._GetNodes(self._data, "material")
        currentTag = parentTag
        currentTag[c4d.TEXTURETAG_MIX] = True
        if blendNode.getAttribute("vray") == "true":
            vray = True
        else:
            vray = False
            
        #For each Submat slot in the XML, check if it refers to a Blend mat, and if it doesn't exist yet create it..
        submats = []
        submats.append(["base_material","material1"])
        submats.append(["coatMaterial0","material2"])
        submats.append(["coatMaterial1"])
        submats.append(["coatMaterial2"])
        submats.append(["coatMaterial3"])
        if vray:
            amountToCheck = 5 #Max VrayBlend has up to 5 mats
            toggle = 0
        else:
            amountToCheck = 2 #Max StdBlend has only 2 mats
            toggle = 1
        for i in xrange(amountToCheck):
            isBlendMat = False
            thisMatName = blendNode.getAttribute(self.NAME)
            if blendNode.hasAttribute(submats[i][toggle]):
                for xmlBlendNode in allBlendNodes:
                    if xmlBlendNode.getAttribute("name") == blendNode.getAttribute(submats[i][toggle]):
                        isBlendMat = True
                        newBlendNode = xmlBlendNode
            if isBlendMat:
                #Run Recursion
                if self._vrayMaterials:
                    currentTag[c4d.TEXTURETAG_MIX] = True
                self._applyBlendSubmats(currentTag,newBlendNode,obj)
            else:
                #Insert Tag
                actualSubMat = self._GetMaterials(blendNode.getAttribute(submats[i][toggle]))
                if len(actualSubMat)!=0:
                    if i>0:
                        texTag = c4d.BaseTag(c4d.Ttexture)
                        texTag.SetData(currentTag.GetData())
                        texTag[c4d.TEXTURETAG_PROJECTION] = 6
                        obj.InsertTag(texTag,currentTag)
                        currentTag = texTag
                    currentTag.SetMaterial(actualSubMat[0])
                    if self._vrayMaterials:
                        currentTag[c4d.TEXTURETAG_MIX] = True
        return currentTag
        
    def _applyMissingBlendMats(self,doc,data):
    
        #Check all xml 'geometry' nodes for blendmat assignments and apply if not already applied
        geomNodes = self._GetNodes(data, "geometry")
        blendNodes = self._GetNodes(data, "blendmaterial")
        matNodes = self._GetNodes(data, "material")
        
        for geomNode in geomNodes:
            if geomNode.hasAttribute("name"):
                objName = geomNode.getAttribute("name")
                obj = doc.SearchObject(objName)
                if obj is not None:
                    hasBlendInMatList = False
                    blendList = []
                    if geomNode.hasAttribute("matList"):
                        matListS = geomNode.getAttribute("matList")
                        matList = matListS.split(",")
                        for stdMat in matList:
                            for blendNode in blendNodes:
                                if blendNode.getAttribute("name") == stdMat:
                                    hasBlendInMatList = True
                                    blendList.append(stdMat)
                    if geomNode.hasAttribute("blendMat"):
                        blendList.append(geomNode.getAttribute("blendMat"))
                    #print "BLEND LIST ======= "+str(blendList)
                    if len(blendList) > 0:
                        for blendMatFromList in blendList:
                            blendMatName = blendMatFromList
                            for blendNode in blendNodes:
                                if blendNode.getAttribute("name") == blendMatName:
                                    
                                    blendDataNode = blendNode
                                    
                                    if blendDataNode.getAttribute("vray") == "true":
                                        vray = True
                                    else:
                                        vray = False
                                    tagToFind = ""
                                    actualBlendMat = self._GetMaterials(blendMatName)
                                    if blendDataNode.hasAttribute("base_material"):
                                        baseMatName = blendDataNode.getAttribute("base_material")
                                        actualBaseMat = self._GetMaterials(baseMatName)
                                    # if vray:
                                        # if len(actualBaseMat)!=0:
                                            # actualBaseMatName = actualBaseMat[0].GetName()
                                            # if "BLEND" in actualBaseMatName:
                                                # actualBaseMatName = actualBaseMatName.replace("BLEND","")
                                            # tagToFind = actualBaseMatName
                                    # else:
                                    if len(actualBlendMat)!=0:
                                        actualBlendMatName = actualBlendMat[0].GetName()
                                        if "BLEND" in actualBlendMatName:
                                            actualBlendMatName = actualBlendMatName.replace("BLEND","")
                                        tagToFind = actualBlendMatName
                                    found = []
                                    if tagToFind != "":
                                        tags = obj.GetTags()
                                        for tag in tags:
                                            if tag.GetType()==c4d.Ttexture:
                                                if tag.GetMaterial().GetName()==tagToFind:
                                                    found.append(tag)
                                    #if len(found) == 0:
                                        # print "FOUND NONE"
                                        # newTag = c4d.BaseTag(c4d.Ttexture)
                                        # newTag[c4d.TEXTURETAG_PROJECTION] = 6
                                        # if self._vrayMaterials:
                                            # newTag[c4d.TEXTURETAG_MIX] = True
                                        # obj.InsertTag(newTag)
                                        # found.append(newTag)
                                    if len(found) > 0:
                                        submats = []
                                        submats.append(["base_material","material1"])
                                        submats.append(["coatMaterial0","material2"])
                                        submats.append(["coatMaterial1"])
                                        submats.append(["coatMaterial2"])
                                        submats.append(["coatMaterial3"])
                                        if vray:
                                            amountToCheck = 5 #Max VrayBlend has up to 5 mats
                                            toggle = 0
                                        else:
                                            amountToCheck = 2 #Max StdBlend has only 2 mats
                                            toggle = 1            
                                        for t in xrange(len(found)):
                                            currentTag = found[t]
                                            #Check all slots to see if this BlendMat has a sub Blend mat in it..
                                            hasBlendMat = False
                                            for i in xrange(amountToCheck):
                                                if blendDataNode.hasAttribute(submats[i][toggle]):
                                                    for subblendNode in blendNodes:
                                                        if subblendNode.getAttribute("name") == blendDataNode.getAttribute(submats[i][toggle]):
                                                            hasBlendMat = True
                                            for i in xrange(amountToCheck):
                                                isBlendMat = False
                                                #For each submat, check if its in XML Blend list, and if so do some shit..
                                                if blendDataNode.hasAttribute(submats[i][toggle]):
                                                    for subblendNode in blendNodes:
                                                        if subblendNode.getAttribute("name") == blendDataNode.getAttribute(submats[i][toggle]):
                                                            isBlendMat = True
                                                            subBlendData = subblendNode
                                                actualSubmat = self._GetMaterials(blendDataNode.getAttribute(submats[i][toggle])) 
                                                if i==0:
                                                    if self._vrayMaterials:
                                                        if not hasBlendMat: 
                                                            #No SubBlend Mats - Just apply VrayBlend
                                                            currentTag.SetMaterial(actualBlendMat[0])
                                                        else:
                                                            if not isBlendMat:
                                                                if len(actualSubmat)!=0:
                                                                    #Has SubBlend but not this first slot - Just apply slot material ( no VrayBlend )
                                                                    currentTag.SetMaterial(actualSubmat[0])
                                                                    currentTag[c4d.TEXTURETAG_MIX] = True
                                                    else:
                                                        if len(actualSubmat)!=0:
                                                            #Std Import - apply slot material either way
                                                            currentTag.SetMaterial(actualSubmat[0])
                                                if not self._vrayMaterials or isBlendMat:
                                                    if len(actualSubmat)!=0:
                                                        if i==0:
                                                            if self._vrayMaterials:
                                                                #Already checked if it's not a SubBlend - so apply and do SubBlend recursion
                                                                #print "APPLYING = "+actualSubmat[0].GetName()
                                                                currentTag.SetMaterial(actualSubmat[0])
                                                                currentTag[c4d.TEXTURETAG_MIX] = True
                                                                currentTag = self._applyBlendSubmats(currentTag,subBlendData,obj)
                                                            else:
                                                                if isBlendMat:
                                                                    #Already applied slot material for Std Import - so if it's SubBlend do recursion
                                                                    currentTag = self._applyBlendSubmats(currentTag,subBlendData,obj)
                                                        else:
                                                            #Not first slot ( and is either std import or isBlendMat ) - so create new tag and if SubBlend do recursion
                                                            newTag = c4d.BaseTag(c4d.Ttexture)
                                                            newTag.SetData(currentTag.GetData())
                                                            newTag.SetMaterial(actualSubmat[0])
                                                            obj.InsertTag(newTag,currentTag)
                                                            currentTag = newTag
                                                            if self._vrayMaterials:
                                                                currentTag[c4d.TEXTURETAG_MIX] = True
                                                            if isBlendMat:
                                                                currentTag = self._applyBlendSubmats(currentTag,subBlendData,obj)
                                                    elif isBlendMat:
                                                        currentTag = self._applyBlendSubmats(currentTag,subBlendData,obj)
                                                        if self._vrayMaterials:
                                                            currentTag[c4d.TEXTURETAG_MIX] = True
                                                elif self._vrayMaterials:
                                                    if not isBlendMat and hasBlendMat:
                                                        if len(actualSubmat)!=0:
                                                            #Catchall - it's Vray Import and does include a blendmat somewhere ( not this one though ), so create tag and apply.
                                                            newTag = c4d.BaseTag(c4d.Ttexture)
                                                            newTag.SetData(currentTag.GetData())
                                                            newTag.SetMaterial(actualSubmat[0])
                                                            obj.InsertTag(newTag,currentTag)
                                                            currentTag = newTag
                                                            currentTag[c4d.TEXTURETAG_MIX] = True
    
    def _importFbx(self, doc):
        """import fbx.
        """
        
        filePath = self.DIR_CURRENT+"/CACA.fbx"
        
        if not os.path.exists(filePath):
            gui.MessageDialog("Could not find file to import at "+filePath)
            return False
        
        if Import.IMPORT_OPTIONS:
            documents.LoadFile(filePath)
        else:
            file = documents.LoadDocument(filePath, c4d.SCENEFILTER_OBJECTS | c4d.SCENEFILTER_MATERIALS | c4d.SCENEFILTER_MERGESCENE)
            documents.InsertBaseDocument(file)
    
    def _checkAuth(self, bc):
        self.bc = c4d.plugins.GetWorldPluginData(AUTH_PLUGIN_ID)
        if self.bc:
            if not self.bc[self.DSET]:
                c4d.CallCommand(1033606)
        else:
            c4d.CallCommand(1033606)
        self.bc = c4d.plugins.GetWorldPluginData(AUTH_PLUGIN_ID)
        if not self.bc.GetBool(1005):
            return False
        return True
    
    def timeMe(self, func, data,data2=None):
        t0 = time.clock()
        if data2 is not None:
            func(data,data2)
        else:
            func(data)
        print str(self.funcNum)+" = "+str(100*(time.clock() - t0))[0:4]+" ("+str(func)+")"
        self.funcNum +=1
    
    def reloadAllShaders(self):
        VRAY_SHADER_WRAPPER = 1026701
        VRAY_SHADERS_RELOADIMAGE = 1004
        for mat in self._doc.GetMaterials():
            shader = mat.GetFirstShader()
            while shader is not None:
                if shader.GetType() == VRAY_SHADER_WRAPPER:
                    res = shader.Message( c4d.MSG_DESCRIPTION_COMMAND , { 'id':VRAY_SHADERS_RELOADIMAGE } ) #reload image
                    c4d.GePrint(shader.GetName() + " " + str(res));
                    
                shader = shader.GetNext()
        c4d.EventAdd()
    
    def patchTime(self):
        mats = self._doc.GetMaterials()
        for mat in mats:
            if mat.GetName()=="VR_pistil":
                mat[c4d.VRAYMATERIAL_BUMP_BUMPTEXMULT] = 0.1
            elif mat.GetName()=="VR_flower":
                mat[c4d.VRAYMATERIAL_BUMP_BUMPTEXMULT] = 0.1
    
    def Execute(self, doc):
        
        print "Import"
        vrayversion = False
        try:
        	vrayversion = c4d.plugins.FindPlugin(1021144)
        	vrayversion = vrayversion.GetFilename()
        	if ("V3" in vrayversion): self.VRAY3 = True
        except:
        	print "no vray"

        if int(str(c4d.GetC4DVersion())[0:2]) > 18:
            gui.MessageDialog("This version of the MaxToC4D plugin does not officially support versions of Cinema4D above R18.")
        else:
            c4d.CallCommand(AUTH_PLUGIN_ID)
            
            bc = c4d.plugins.GetWorldPluginData(AUTH_PLUGIN_ID)
            if not bc.GetBool(101):
                return False
            
            bc = c4d.plugins.GetWorldPluginData(CONFIG_PLUGIN_ID)
            
            if (bc is not None):
                self.CB_OP_CURRENT = bc.GetBool(CB_OP_CURRENT_ID)
                self.NUM_PA_CURRENT = bc.GetReal(NUM_PA_CURRENT_ID)
                self.CB_UT_CURRENT = bc.GetBool(CB_UT_CURRENT_ID)
                self.NUM_EA_CURRENT = bc.GetReal(NUM_EA_CURRENT_ID)
                self.CB_UP_CURRENT = bc.GetBool(CB_UP_CURRENT_ID)
                self.DIR_CURRENT = bc.GetFilename(DIR_CURRENT_ID)
            else:
                self.CB_OP_CURRENT = True
                self.NUM_PA_CURRENT = 31
                self.CB_UT_CURRENT = True
                self.NUM_EA_CURRENT = 0.1
                self.CB_UP_CURRENT = False
                self.DIR_CURRENT = c4d.storage.GeGetC4DPath(c4d.C4D_PATH_MYDOCUMENTS)+"\TEMP3D"
            
            self._pluginPath = __file__[:(__file__.index("Import"))]
            
            if self.__dialog is None:            
                self.__dialog = ImportMessageDialog()
                self.__dialog._res = __res__
            screen = c4d.gui.GeGetScreenDimensions(0,0,True)
            self.__dialog.Open(c4d.DLG_TYPE_MODAL_RESIZEABLE, PLUGIN_ID,screen['sx2']/2-220,screen['sy2']/2-220)
            
            if Import.IMPORT_MODE==1:
                # Vray
                self._quickMode = False
                self._usingOctane = False
                self._vrayMaterials = True
                self._vrayLights = True
                self._vrayCameras = True
            elif Import.IMPORT_MODE==2:
                # Octane
                self._quickMode = False
                self._usingOctane = True
                self._vrayMaterials = False
                self._vrayLights = False
                self._vrayCameras = False
            elif Import.IMPORT_MODE==3:
                # Standard
                self._quickMode = False
                self._usingOctane = False
                self._vrayMaterials = False
                self._vrayLights = False
                self._vrayCameras = False
            else:
                # Quickmode
                self._quickMode = True
                self._usingOctane = False
                self._vrayMaterials = False
                self._vrayLights = False
                self._vrayCameras = False
            
            doc.StartUndo()
            self._importFbx(doc)
            doc = documents.GetActiveDocument()
            self._cleanPolygonObjects(doc)
            
            c4d.EventAdd(c4d.MSG_UPDATE)
            
            self._doc = doc
            
            if int(str(c4d.GetC4DVersion())[0:2]) < 16:
                self.R16 = False
            elif int(str(c4d.GetC4DVersion())[0:2]) >= 18:
                self.R18 = True
                
            if (self.R18):
                self.REFLECTION_LAYERID = 4
            else:
                self.REFLECTION_LAYERID = 5
            
            #c4d.gui.MessageDialog("This is the DEMO version of the Max2C4D Importer and will expire after a certain time.")
            
            rd = self._doc.GetActiveRenderData()   
            rd[c4d.RDATA_TEXTUREERROR]=0
            
            data = self._LoadFile()
            self._data = data
            
            self.createdBlendMatList = []
            self._tempObjects = []
            # self.funcNum = 0
            # self.timeMe(self._GetFileUnits,data)
            # self.timeMe(self._SetMaterials,data)
            # self.timeMe(self._SetBlendMaterials,data)
            # self.timeMe(self._SetTwoSidedMaterials,data)
            # self.timeMe(self._SetOverrideMaterials,data)
            # self.timeMe(self._SetCarPaintMaterials,data)
            # self.timeMe(self._SetBackground,data)
            # self.timeMe(self._SetColors,data)
            # self.timeMe(self._SetLights,data)
            # self.timeMe(self._SetCameras,data)
            # self.timeMe(self._SetTurboSmooth,data)
            # self.timeMe(self._SetRenders,data)
            # self.timeMe(self._SetMatteObjects,data)
            # self.timeMe(self._cleanEmptyTexSlots,doc)
            # self.timeMe(self._applyMultiSubMatsCorrectly,doc)
            # self.timeMe(self._applyMissingBlendMats,doc,data)
            
            self._GetFileUnits(data)
            self._SetMaterials(data)
            self._SetBlendMaterials(data)
            self._SetTwoSidedMaterials(data)
            self._SetFastSSS2Materials(data)
            self._SetOverrideMaterials(data)
            self._SetCarPaintMaterials(data)
            self._SetLightMaterials(data)
            #self._SetVrayProxyObjects(data)
            self._SetVrayProxyObjects2()
            self._SetBackground(data)
            self._SetColors(data)
            self._SetLights(data)
            self._SetCameras(data)
            self._SetTurboSmooth(data)
            self._SetDisplacementMaterials(data)
            self._SetRenders(data)
            self._SetMatteObjects(data)
            self._cleanEmptyTexSlots(doc)
            self._applyMultiSubMatsCorrectly(doc)
            self._applyMissingBlendMats(doc,data)
            self.patchTime()
            
            rd = self._doc.GetActiveRenderData()
            rd[c4d.RDATA_SAVEIMAGE] = 0
            
            #c4d.EventAdd(c4d.EVENT_0)
            
            doc.EndUndo()
            
            c4d.CallCommand(12168) #Remove Unused Materials
            c4d.CallCommand(12211) #Remove Duplicate Materials
            c4d.CallCommand(12333) #Sort Materials
            
            for mat in doc.GetMaterials():
                matName = mat.GetName()
                if matName[0:4] == "OCT_":
                    mat.SetName(matName[4:])
            for tempObj in self._tempObjects:
                tempObj.Remove()
                        
            if (self._vrayMaterials):
                c4d.CallCommand(12092)
            #self.reloadAllShaders()
            
            # except Exception as exc:
                # print "--------------------------------------"
                # print "Exception:"
                # print str(sys.exc_info()[2].tb_lineno)
                # print str(exc)
                # print "--------------------------------------"
                # self._ThrowError()
        return True

if __name__ == "__main__":

    icon = c4d.bitmaps.BaseBitmap()
    icon.InitWith(os.path.join(os.path.dirname(__file__), "res", "Icon.tif"))
    print "Start"
    c4d.plugins.RegisterCommandPlugin(PLUGIN_ID, "Import", 0, icon, "Set materials, render and lights settings based on XML file.", Import())
